如何处理 nodejs C++ 模块中的映射参数
How to handle a map argument in a nodejs C++ module
我有一个用于 nodejs 的 C++ 模块。我需要接受一个 key/value 对作为方法的参数。
var my_map = {'key1': 'value1','key2': 'value2'};
不确定之后要做什么:
void MyClient::AcceptData(const FunctionCallbackInfo<Value>& args)
{
Isolate* isolate = args.GetIsolate();
if (args.Length() != 1)
{
isolate->ThrowException(v8::Exception::TypeError(String::NewFromUtf8(isolate,
"Usage: Key/Value Map")));
return;
}
// It returns true for args[0]->isObject(), but not for args[0]->IsMap()
// Now what? How do I get a C++ map out of args[0] ?
// What do I cast it into?
}
如果确定是Map对象,可以通过这段代码获取:
Handle<Map> map = Handle<Map>::cast(args[0]);
然后使用地图的特性和属性。
希望对您有所帮助。
好的,我找到答案了...
v8::Local<v8::Object> obj = args[0]->ToObject();
v8::Local<v8::Array> props = obj->GetPropertyNames();
std::map<std::string, std::string> theMap;
for (unsigned int i = 0; i < props->Length(); i++)
{
char key[1000], value[1000];
props->Get(i)->ToString()->WriteUtf8(key, 1000);
obj->Get(props->Get(i))->ToString()->WriteUtf8(value, 1000);
theMap.insert(std::make_pair(key, value));
}
我有一个用于 nodejs 的 C++ 模块。我需要接受一个 key/value 对作为方法的参数。
var my_map = {'key1': 'value1','key2': 'value2'};
不确定之后要做什么:
void MyClient::AcceptData(const FunctionCallbackInfo<Value>& args)
{
Isolate* isolate = args.GetIsolate();
if (args.Length() != 1)
{
isolate->ThrowException(v8::Exception::TypeError(String::NewFromUtf8(isolate,
"Usage: Key/Value Map")));
return;
}
// It returns true for args[0]->isObject(), but not for args[0]->IsMap()
// Now what? How do I get a C++ map out of args[0] ?
// What do I cast it into?
}
如果确定是Map对象,可以通过这段代码获取:
Handle<Map> map = Handle<Map>::cast(args[0]);
然后使用地图的特性和属性。
希望对您有所帮助。
好的,我找到答案了...
v8::Local<v8::Object> obj = args[0]->ToObject();
v8::Local<v8::Array> props = obj->GetPropertyNames();
std::map<std::string, std::string> theMap;
for (unsigned int i = 0; i < props->Length(); i++)
{
char key[1000], value[1000];
props->Get(i)->ToString()->WriteUtf8(key, 1000);
obj->Get(props->Get(i))->ToString()->WriteUtf8(value, 1000);
theMap.insert(std::make_pair(key, value));
}