我正在尝试使用节点ffi包装c代码。但是有一个c函数调用了一个参数中的函数,我在web上搜索了一下,但是没有找到任何合适的方法来使用node ffi包装同一个函数。
这是我以前试过的(片段),
示例.js
var intPin = 40;
var state = 0;
var lib = require('./c_functions');
lib.c_functions.attachInterrupt(intPin,abc); //attachInterrupt is a c function and **Problem 1**
function abc(){
console.log("state: ",state);
state++;
}
c_functions.js//file访问库并导出函数
var ffi = require('ffi'); //requires to use node-ffi functionalities
var ref = require('ref'); //reference to integer type
var int = ref.types.int;
var voidtype = ref.types.void;
var objPtr = ref.refType(voidType); //void pointer
var c_functions = ffi.Library('/usr/local/lib/lib.so.0.5.0', { //accessing so file
"attachInterrupt":[voidtype, [int,objPtr]] // **Problem 2**
});
/**
* @breif Definitions for Pin modes
*/
var INPUT = 0;
var OUTPUT = 1;
/**
* @breif Definitions for pin values
*/
var LOW = 0;
var HIGH = 1;
module.exports = {c_functions , HIGH, LOW, INPUT, OUTPUT}; //exporting functions
所以我有两个问题,
一。问题2(在代码中)-attachintrupt函数的第二个参数的类型应该是什么?
2。问题1(在代码中)-如何调用作为参数传递的函数?
请帮忙!谢谢。
最佳答案
我认为您需要的是ffi.Callback()它基本上返回一个指针,可以传递给C函数:
您的问题的解决方案如下所示(example.js):
const intPin = 40;
const state = 0;
const lib = require('./c_functions');
const abc = () => {
console.log("state: ",state);
state++;
}
const pointerToMyFunction = ffi.Callback('void', [], abc);
//now pass pointer of abc() to attachInterrupt function
lib.c_functions.attachInterrupt(intPin,pointerToMyFunction);
ffi.Callback
接受返回类型、参数类型和javascript函数作为参数,并返回指向此函数的指针。我将空数组作为第二个参数传递,因为abc()
不接受任何内容。你可以在上面的链接中看到更多的例子。(也尝试使用
const
和let
而不是var
:d)关于c - C函数将函数作为参数传递,如何使用node-ffi包装该函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58091811/