想在Electron项目里加一个C++的SDK,所以就开始挖坑填坑了,深入研究了一下后发一份ffi-napi的食用指南供后人参考
1、简单参数函数的调用
略
2、结构体参数函数的调用
略
3、结构体参数回调函数的调用
首先定义一个查看C++中的结构体,并定义一个函数,参数为回调函数,回调函数参数为结构体,我的是这样的
typedef struct apple { char name[64]; char password[64]; int id; }Apple; extern "C" __declspec(dllexport) void test(void (STDCALL* ss)(Apple)) { setlocale(LC_ALL, "zh_CN.UTF-8"); Apple a = { "test","123455" ,128}; ss(a); }
JS中还原此结构体,执行上面C++的函数,传入一个回调函数
var ffi = require('ffi-napi'); const ref = require('ref-napi') const ArrayType = require('ref-array-napi') const StructType = require ('ref-struct-napi') var apple=StructType({ name: ArrayType(ref.types.char, 64), password:ArrayType(ref.types.char, 64), id: ref.types.int32 }) var libm = ffi.Library('Dll1.dll', { 'test':['void',['pointer']] });
//定义一个回调函数,作为C++函数的参数传入,该回调函数的参数为结构体 const callback=ffi.Callback(ref.types.void,[apple],(a)=>{ console.log(a.name.buffer.toString("utf-8")); //重点一,结构体里的字符串是这样取出来的 console.log(a.password.buffer.toString("utf-8")); console.log(a.id);//重点二,数字是这样取出来的 }) //执行C++中定义的函数 libm.test(callback);
本文重点在研究如何将回调函数返回的结构体中的变量取出,若对你没有帮助,请选择继续 Google × Baidu √
2022年5月28日,因为ffi-napi无法完成异步等线程操作,故改用node-api来调用第三方SDK完成功能,具体用法可看下一篇博客