如何在Node.js调用C++ DLL的回调中正确传递enum类型参数
错误原因
- C++ 枚举类型
GUIENUM默认底层类型为int,你将其对应为ref.types.void属于类型不匹配,是触发类型转换错误的核心原因 - 无参数的
Start、Stop函数的ffi定义参数列表错误写为[ref.types.void],正确无参函数参数列表应为空数组 - 回调函数如果未被全局引用会被V8 GC自动回收,后续调用时会触发野指针异常
修复后代码
var ffi = require("ffi-napi") var ref = require("ref-napi"); const constString = ref.types.CString; // C++ enum默认底层类型为int,使用int类型对应枚举参数 const guiEnumType = ref.types.int; // 修正回调参数类型列表 const callback = ffi.Callback(ref.types.void, [guiEnumType, constString], function (sec, data) { // 可选:做枚举值到名称的映射,方便调试 const GUI_ENUM_MAP = { 0: 'START', 1: 'STOP', 2: 'DEBUG', 3: 'STATUS' } console.log('枚举值:', sec); console.log('枚举含义:', GUI_ENUM_MAP[sec]); console.log('回调消息:', data); }); const libloc = "./Dll1.dll"; const ces = ffi.Library(libloc, { 'SetCallBackMethod': [ref.types.void, ['pointer']], // 无参函数参数列表为空数组 'Start': [ref.types.void, []], 'Stop': [ref.types.void, []], }); // 将回调挂载到导出对象上,避免被GC回收 ces.callback = callback; ces.SetCallBackMethod(callback); ces.Start(); ces.Stop(); module.exports = ces;
说明
C++侧代码无需修改,重新编译DLL后运行Node.js代码即可正常接收枚举值和回调消息。
内容的提问来源于stack exchange,提问作者Soumya Pai
相关产品推荐
相关产品推荐

