zhangyuang / node-ffi-rs

Implement ffi in Node.js by Rust and NAPI
MIT License
163 stars 6 forks source link

How do I load multiple functions at once from a library? #28

Closed Axiver closed 5 months ago

Axiver commented 5 months ago

I have the following code that I want to migrate over from ffi-napi to ffi-rs:

var aubio = ffi.Library('libaubio', {
    // fvec
    "new_fvec": [ "pointer", [ "int" ]],
    "del_fvec": [ "void", [ "pointer" ]],
    "fvec_get_sample": [ "float", [ "pointer", "int" ]],
    "fvec_set_sample": [ "void", [ "pointer", "float", "int" ]],
    "fvec_get_data": [ "float", [ "pointer" ]],
    "fvec_print": [ "void", [ "pointer" ]],
    "fvec_set_all": [ "void", [ "pointer", "float" ]],
    "fvec_zeros": [ "void", [ "pointer" ]],
    "fvec_rev": [ "void", [ "pointer" ]],
    "fvec_weight": [ "void", [ "pointer", "pointer" ]],
    "fvec_copy": [ "void", [ "pointer", "pointer" ]],
    "fvec_ones": [ "void", [ "pointer" ]],
    ...

Is there any method built-into ffi-rs for me to load the functions all with one method call? Instead of having to iterate through and call load() on them one by one. Thank you.

zhangyuang commented 5 months ago

Yeah, you need to call load function for each method, ffi-rs will cache foreign function symbol so you don't need to worry performance.

In the future, maybe we can also support load multiply methods in a single call

zhangyuang commented 5 months ago

In ffi-rs@1.0.62, you can use define methods to define a function signature

const res = define({
  sum: {
    library: "libsum",
    retType: DataType.I32,
    paramsType: [DataType.I32, DataType.I32],
  },
  atoi: {
    library: "libnative",
    retType: DataType.I32,
    paramsType: [DataType.String],
    paramsValue: ["1000"],
  }
})
equal(res.sum([1, 2]), 3)
equal(res.atoi(["1000"]), 1000)