node.js - 是否可以使用 ref-struct 和 ref-array 创建结构数组?

标签 node.js node-ffi

我正在使用 node-ffi 调用一个函数,该函数将输出参数作为指向结构数组的指针的指针。有没有办法让我使用 ref-struct 和 ref-array 来访问我得到的数组?

struct = require("ref-struct");
var rect_type = struct({
    'x': 'int',
    'y': 'int',
    'width': 'int',
    'height': 'int',
});
var rotation_type = struct({
    'yaw': 'short',
    'pitch': 'short',
    'roll': 'short'
});
var face_type = struct({
    'rect' : rect_type,
    'rotation' : rotation_type,
    'confidence' : 'double'
});

我能够在函数调用后从指针中获取第一个结构,但无法获取数组的其余部分:

var mylib = ffi.Library('lib/libN', {
    'GetFaces' : [ 'int', [ 'pointer' ] ]
});

var pface_type = ref.refType(face_type);
var ppface = ref.alloc(pface_type);

result = mylib.GetFaces(ppface);

face = ppface.deref().deref();

console.log("X:" + face.rect.x + " Y:" + face.rect.y);

有没有办法将参数声明为结构数组?我试过这个但它不起作用:

var array = require("ref-array");
var face_array = array(face_type)
var p_face_array = ref.refType(face_array);
var ppface = ref.alloc(p_face_array);
result = mylib.GetFaces(ppface);

最佳答案

作为引用,我最终在没有使用 ref-array 的情况下解决了这个问题。

诀窍/黑客是要知道在 C 中,“数组”与指向第一个元素的指针几乎相同。所以在 ffi 中,我们只是传递一个指向第一个元素的指针,并且要非常小心不要越界。

var pface_type = ref.refType(face_type);
var mylib = ffi.Library('lib/libN', {
    'GetFaces' : [ 'int', [ ref.refType('int'), pface_type ] ]
});

var ppface = ref.alloc(pface_type);
var face_count = ref.alloc('int');

result = mylib.GetFaces(face_count, ppface);

var faces = [];
var count = faceCount.deref();

if(count > 0)
{
    var face_array = ppface.readPointer(0, count * face_type.size);
    var i = 0;
    for(i = 0; i < count; i++)
    {
        var face = ref.get(face_array, i * face_type.size, face_type)
        console.log("X:" + face.rect.x + " Y:" + face.rect.y);        
    }
}

关于node.js - 是否可以使用 ref-struct 和 ref-array 创建结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20835782/

相关文章:

javascript - 使用 EJS 模板的 Express 应用程序给出错误 : Failed to lookup view "/id" in views directory "/home/USER/Desktop/scholarship-app/views"

node.js - 改进express.js模块的使用

node.js - Marklogic 9 + Roxy : can't connect to created database using Node. js

node.js - 在 Mongoose 中添加动态集合名称查找数据

node.js - 从 Node js调用带有pAnisChar的Delphi stdcall函数

node.js - node-ffi - 将字符串指针传递给 C 库

javascript - Node-ffi 为 C 函数抛出 'undefined symbol' 错误

c++ - 如何在nodejs中使用C++ api?

node.js - 我收到 "error message: Process exited before completing request"

javascript - 为什么 EnumPrintersA 和 EnumPrintersW 请求相同数量的内存?