binding.cc 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include <node_api.h>
  2. #include <node_buffer.h>
  3. #include <v8.h>
  4. namespace {
  5. napi_value CreateBuffer(napi_env env, napi_callback_info info) {
  6. v8::Isolate* isolate = v8::Isolate::TryGetCurrent();
  7. if (isolate == nullptr) {
  8. return NULL;
  9. }
  10. const size_t length = 4;
  11. uint8_t* data = new uint8_t[length];
  12. for (size_t i = 0; i < 4; i++) {
  13. data[i] = static_cast<uint8_t>(length);
  14. }
  15. auto finalizer = [](char* data, void* hint) {
  16. delete[] static_cast<uint8_t*>(reinterpret_cast<void*>(data));
  17. };
  18. // NOTE: Buffer API is invoked directly rather than
  19. // napi version to trigger the FATAL error from V8.
  20. v8::MaybeLocal<v8::Object> maybe = node::Buffer::New(
  21. isolate, static_cast<char*>(reinterpret_cast<void*>(data)), length,
  22. finalizer, nullptr);
  23. return reinterpret_cast<napi_value>(*maybe.ToLocalChecked());
  24. }
  25. napi_value Init(napi_env env, napi_value exports) {
  26. napi_status status;
  27. napi_property_descriptor descriptors[] = {{"createBuffer", NULL, CreateBuffer,
  28. NULL, NULL, NULL, napi_default,
  29. NULL}};
  30. status = napi_define_properties(
  31. env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors);
  32. if (status != napi_ok)
  33. return NULL;
  34. return exports;
  35. }
  36. } // namespace
  37. NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)