求教C扩展中如何把对象真实的指针拿到?(已解决)
写了两个C扩展的方法,一个是取出对象指针,一个是通过指针读出对象。但是读取出来的是经过拷贝过对象的指针。并且我重新malloc的数据也不能保存数据,由于C扩展的本质是动态库的关系,所以调用完成后会关闭动态调用就算没free也会释放掉。所以我想拿到真正node进程中这个对象的指针,有没有什么好的方法? 代码奉上,谢谢解答。
var addon = require('bindings')('addon.node')
var obj1 = {a:1,b:2,c:()=>{return a+b;}};
var objaddr1 = addon.getObjectAddr(obj1);
var obj2 = addon.getObjectByAddr(parseInt(objaddr1,16));
var objaddr2 = addon.getObjectAddr(obj2);
console.log(obj1,objaddr1)
console.log(obj2,objaddr2)
#include <nan.h>
void getObjectAddr(const Nan::FunctionCallbackInfo<v8::Value>& info) {
if (info.Length() < 1) {
Nan::ThrowTypeError("Wrong number of arguments");
return;
}
v8::Local<v8::Object> obj = info[0]->ToObject();
// v8::Local<v8::Object> *objP = (v8::Local<v8::Object>*)malloc(sizeof(v8::Local<v8::Object>));
// *objP = obj;
char objAddrStr[20]; //max 0x8000000000000000
sprintf( objAddrStr,"%p",&obj);
// sprintf( objAddrStr,"%p",objP);
v8::Local<v8::String> v8ObjAddrStr = v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), objAddrStr);
info.GetReturnValue().Set(v8ObjAddrStr);
}
void getObjectByAddr(const Nan::FunctionCallbackInfo<v8::Value>& info) {
if (info.Length() < 1) {
Nan::ThrowTypeError("Wrong number of arguments");
return;
}
int64_t addr = info[0]->IntegerValue();
v8::Local<v8::Object> *objP;
objP = (v8::Local<v8::Object> *)addr;
info.GetReturnValue().Set(*objP);
}
void Init(v8::Local<v8::Object> exports) {
exports->Set(Nan::New("getObjectAddr").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(getObjectAddr)->GetFunction());
exports->Set(Nan::New("getObjectByAddr").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(getObjectByAddr)->GetFunction());
}
NODE_MODULE(typePointer, Init)
仓库地址(这里可以down下来直接测试):https://github.com/zy445566/type-pointer