javascript - 如何从 firefox-addon/js-ctypes 调用 C++ 类实例?

标签 javascript c++ firefox-addon jsctypes

我有一个 DLL(带有类似的 C++ 代码):

MyObject::MyObject(TYPEPERIPH typePeriph) {
    m_TypePeriph = typePeriph;
    //..
}

CR MyObject::GetTypePeriph( TYPEPERIPH *typePeriph ) const throw(MY_Exception) {
    *typePeriph = m_TypePeriph;
    //..
    return 0;
}

在 C++ 中调用,就像这样:

MyObject MyObject((TYPEPERIPH)myTypePeriph);
MyObject.GetTypePeriph(&result);

我想用 js-ctypes 调用这个 DLL:

Components.utils.import("resource://gre/modules/ctypes.jsm");
var dll = ctypes.open("my.dll");

var constructor = dll.declare('MyObject',
    ctypes.default_abi,
    ctypes.voidptr_t,
    ctypes.uint8_t
);

var ptr=constructor( 1 ) // ptr seems to be a pointer to an instance

// but how to call this instance ?? should I pass the ptr somewhere ?
var GetTypePeriph = dll.declare('GetTypePeriph',
    ctypes.default_abi,
    ctypes.int,
    ctypes.uint8_t.ptr
);

var result=ctypes.uint8_t(0);
GetTypePeriph(result.address());
myPerif= result.value;

第一部分有效 (^^) ...“ptr”似乎是一个有效的指针。但是我不知道如何用这个指针调用实例方法...

最佳答案

您必须定义 VTABLE,然后创建一个实例,请参见此处 - https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/Examples/Using_COM_from_js-ctypes

上周我还用 js-ctypes 做了一些 COM,我在 Windows 上使用 DirectShow API - https://github.com/Noitidart/ostypes_playground/commits/audio-capture

VTBLE 方法必须有序!!这花了我两个月的时间才弄清楚我是什么时候第一次接触到它的。

这是我做的一堆 COM 东西的定义:https://github.com/Noitidart/ostypes/compare/fb1b6324343d6e19c942bbc0eb46cfcfbe103f35...master

我编辑了你的代码,使其看起来更像它应该的样子:

Components.utils.import("resource://gre/modules/ctypes.jsm");
var dll = ctypes.open("my.dll");

var MyConstructorVtbl = ctypes.StructType('MyConstructorVtbl');
var MyConstructor = ctypes.StructType('MyConstructor', [
    { 'lpVtbl': MyConstructorVtbl.ptr }
]);
MyConstructorVtbl.define([
    {
        'GetTypePeriph': ctypes.FunctionType(ctyes.default_abi,
            ctypes.int, [           // return type
                MyConstructor.ptr,  // arg 1 HAS to be ptr to the instance EVEN though your C++ above doesnt show this. this is how it works.
                ctypes.uint8_t.ptr
            ]).ptr
    }
]);

var constructor = dll.declare('MyObject',
    ctypes.default_abi,
    MyConstructor.ptr.ptr,
    ctypes.uint8_t
);

var ptr=constructor( 1 ) // ptr seems to be a pointer to an instance
var instance = ptr.contents.lpVtbl.contents;

var result=ctypes.uint8_t(0);
instance.GetTypePeriph(ptr, result.address());
myPerif= result.value;

关于javascript - 如何从 firefox-addon/js-ctypes 调用 C++ 类实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37564744/

相关文章:

api - 将 API key 和密码放入我的 Firefox 插件中

javascript - 火狐扩展 : How to access page element via jQuery?

firefox-addon - 使用 SDK 通过 firefox 无重启扩展添加新的搜索引擎

javascript - 使用 Node 请求模块的 UTF8 字符编码

javascript - 尝试打开文本文件时,Python 脚本抛出非常奇怪的错误

c++ - 合并两个几乎相同的类模板

c++ - 如何找出哪个派生类正在处理

javascript - 如何在 React Native 中使用 MapLibre GL Js

javascript - Ajax jquery mysqli 更新

c++ - 应该为传感器读数的串行通信选择什么缓冲区大小?