Skip to content

Instantly share code, notes, and snippets.

@gabrielschulhof
Last active February 13, 2019 22:35
Show Gist options
  • Save gabrielschulhof/7b67df8c19ef2eb3ae85c552ef2055d4 to your computer and use it in GitHub Desktop.
Save gabrielschulhof/7b67df8c19ef2eb3ae85c552ef2055d4 to your computer and use it in GitHub Desktop.
static function address reuse on OSX
#include <assert.h>
#include <node.h>
#include "common.h"
namespace {
void Init(v8::Local<v8::Object> exports,
v8::Local<v8::Object> module,
v8::Local<v8::Context> context) {
v8::Local<v8::Name> propName =
v8::String::NewFromUtf8(context->GetIsolate(), "getModuleName",
v8::NewStringType::kNormal).ToLocalChecked();
v8::Local<v8::Value> propValue =
ReturnModuleName::New(context, NODE_STRINGIFY(NODE_GYP_MODULE_NAME));
exports->Set(context, propName, propValue).FromJust();
}
} // end of anonymous namespace
NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME, Init)
{
'targets': [
{
'target_name': 'binding1',
'sources': [ 'binding.cc' ]
},
{
'target_name': 'binding2',
'sources': [ 'binding.cc' ]
},
]
}
#include <node.h>
// Solution: enclose in anonymous namespace. Uncomment line below and
// corresponding closing brace at the bottom of the file.
// namespace {
class ReturnModuleName {
public:
static inline v8::Local<v8::Function>
New(v8::Local<v8::Context> context, const char* string);
private:
static inline void
Binding(const v8::FunctionCallbackInfo<v8::Value>& info);
};
v8::Local<v8::Function>
ReturnModuleName::New(v8::Local<v8::Context> context, const char* string) {
v8::Local<v8::String> v8string =
v8::String::NewFromUtf8(context->GetIsolate(),
string,
v8::NewStringType::kNormal).ToLocalChecked();
return v8::Function::New(context, Binding, v8string).ToLocalChecked();
}
void
ReturnModuleName::Binding(const v8::FunctionCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(info.Data());
}
// } // end of anonymous namespace
const assert = require('assert');
const bindings = require('bindings');
const binding1 = bindings('binding1');
const binding2 = bindings('binding2');
console.log(binding1.getModuleName());
console.log(binding2.getModuleName());
{
"name": "napi-pr-407",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"bindings": "^1.4.0"
},
"author": "",
"license": "Apache-2.0"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment