如何使用NPAPI创建一个新的JS对象
How to create a new JS object using NPAPI?
我正在写一个NPAPI插件。在c++代码中,我不能使用NPAPI创建JS对象。我试过这个方法:
Foo.js
function Foo(p)
{
this.a=p;
}
Foo.prototype.get=function()
{
return this.a;
}
c++代码(我想创建Foo对象。链接我们在JS中能做的。var s=new Foo(2);)
int newJSObject(const NPP instance,const NPNetscapeFuncs* npnfuncs,const string objectName,
const NPVariant* args,const int argsCount,NPVariant& result)
{
int status;
NPObject *winobj;
npnfuncs->getvalue(instance,NPNVWindowNPObject,&winobj);
NPVariant npJS;
NPIdentifier npJSId=npnfuncs->getstringidentifier(objectName.c_str());
status=npnfuncs->getproperty(instance,winobj,npJSId,&npJS);
NPObject* npObjJS = NPVARIANT_TO_OBJECT(npJS);
NPVariant npPrototype;
NPIdentifier npPrototypeId=npnfuncs->getstringidentifier("prototype");
status=npnfuncs->getproperty(instance,npObjJS,npPrototypeId,&npPrototype);
NPObject* npObjPrototype = NPVARIANT_TO_OBJECT(npPrototype);
NPVariant npJSConstructor;
NPIdentifier npJSConstructorId=npnfuncs->getstringidentifier("constructor");
status=npnfuncs->invoke(instance,npObjPrototype,npJSConstructorId,
args,argsCount,&npJSConstructor);
/*
* destroy memory
* */
npnfuncs->releaseobject(winobj);
npnfuncs->releasevariantvalue(&npJS);
npnfuncs->releasevariantvalue(&npJSConstructor);
result=npJS;
return status;
}
NPVariant jsFoo1;
NPVariant arg;
DOUBLE_TO_NPVARIANT(2,arg);
NPVariant prams[]={arg};
newJSObject(instance,npnfuncs,"Foo",prams,sizeof(prams)/sizeof(prams[0]),jsFoo);
NPVariant jsFoo2;
NPVariant arg;
DOUBLE_TO_NPVARIANT(3,arg);
NPVariant prams[]={arg};
newJSObject(instance,npnfuncs,"Foo",prams,sizeof(prams)/sizeof(prams[0]),jsFoo);
但是如果我们返回jsFoo1和jsFoo2到JS代码,那么我们调用Fooxxx.get()。jsFoo1和jsFoo2都是3。我知道问题是"constructor"
谁能给我另一个方法来创建JS对象在c++中使用NPAPI?
NPN_Construct似乎对浏览器对象不起作用,所以没有直接的方法来做你想做的事情。然而,你可以做的是创建一个javascript函数来为你创建对象并返回它;你甚至可以使用NPN_Evaluate将其自动注入到页面中。
像这样:
function __create_object_2_params(obj, param1, param2) {
return new obj(param1, param2);
}
FireBreath在一些地方使用了类似的技巧。
我不知道你的代码出了什么问题,但我知道当我需要一个NPAPI插件时,以下项目使它变得非常容易:
FireBreath - "一个框架,允许轻松创建强大的浏览器插件"
nixysa - " NPAPI插件的glue代码生成框架"
这两个项目都为你做了所有艰苦的工作,所以你可以在一边创建简单的c++类,并在另一边轻松地将它们用作JS对象。如果你对NPAPI的东西没有太多的投资,我建议你试一试。可以省去很多麻烦。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 如何使用 Node.js 开发一个侦听器来接收许多车辆跟踪数据(通过 TCP)
- 可以在Go中编写一个本地Node.js扩展,而不是C++吗
- 是否有一个可下载的 eclipse 包,我可以将其用于 Java、c++ 和 JS
- 我应该包装一个完全包含在node.js函数中的C++对象吗
- 如何从一个 QtScript .js 文件中调用另一个 QtScript .js文件
- 我如何使用std::string在一个c++插件的Node.js
- 应该如何绑定.用OpenNI编写一个Node.js插件
- 如何为c++代码创建一个dll(在树形程序中使用大量指针),以便在ASP. js中引用它.Net Web应用程序
- 如何从一个Node.js c++插件传递一个关联数组到js代码
- 在Node.js和v8中调用一个使用包装对象作为参数的函数
- 如何使用NPAPI创建一个新的JS对象
- 我怎么能转义字符串,以确保它是一个有效的字符串文字在JS源
- C++,Qt,QtWebKit:如何创建一个html呈现窗口,以便您的应用程序从JS调用中获得回调
- C++,win32api:如何创建一个html呈现窗口,以便您的应用程序从JS调用中获得回调
- 终端服务器上的IPC,带有一个nw.js/node.js/node-namemodule(C++)
- Node.js C++将多个CC文件扩展为一个模块