• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <node_api.h>
2 #include <memory>
3 #include <string>
4 #include "../../js-native-api/common.h"
5 
6 // This test verifies that use of the NAPI_MODULE in C++ code does not
7 // interfere with the C++ dynamic static initializers.
8 
9 namespace {
10 
11 // This class uses dynamic static initializers for the test.
12 // In production code developers must avoid dynamic static initializers because
13 // they affect the start up time. They must prefer static initialization such as
14 // use of constexpr functions or classes with constexpr constructors. E.g.
15 // instead of using std::string, it is preferrable to use const char[], or
16 // constexpr std::string_view starting with C++17, or even constexpr
17 // std::string starting with C++20.
18 struct MyClass {
19   static const std::unique_ptr<int> valueHolder;
20   static const std::string testString;
21 };
22 
23 const std::unique_ptr<int> MyClass::valueHolder =
24     std::unique_ptr<int>(new int(42));
25 // NOLINTNEXTLINE(runtime/string)
26 const std::string MyClass::testString = std::string("123");
27 
28 }  // namespace
29 
30 EXTERN_C_START
Init(napi_env env,napi_value exports)31 napi_value Init(napi_env env, napi_value exports) {
32   napi_value cppIntValue, cppStringValue;
33   NODE_API_CALL(env,
34                 napi_create_int32(env, *MyClass::valueHolder, &cppIntValue));
35   NODE_API_CALL(
36       env,
37       napi_create_string_utf8(
38           env, MyClass::testString.c_str(), NAPI_AUTO_LENGTH, &cppStringValue));
39 
40   napi_property_descriptor descriptors[] = {
41       DECLARE_NODE_API_PROPERTY_VALUE("cppIntValue", cppIntValue),
42       DECLARE_NODE_API_PROPERTY_VALUE("cppStringValue", cppStringValue)};
43 
44   NODE_API_CALL(env,
45                 napi_define_properties(
46                     env, exports, std::size(descriptors), descriptors));
47 
48   return exports;
49 }
50 EXTERN_C_END
51 
52 NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
53