zhangyuang / node-ffi-rs

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

使用Rust编写的C标准动态库,对入参String修改后(字符串追加),似乎这一行之后的所有代码都不执行了 #56

Closed wangxiaoyan369 closed 5 months ago

wangxiaoyan369 commented 5 months ago

环境信息:

node: v20.15.0
npm: 10.7.0
ffi-rs: 1.0.83,ffi-rs-win32-ia32-msvc、ffi-rs-win32-x64-msvc
platform: win32
rustc: 1.79.0

rust代码: lib.rs

#[no_mangle]
pub extern "C" fn add(a: i32, b: i32) -> i32 {
    return a + b;
}

#[no_mangle]
pub extern "C" fn modify_string(s: &mut String) {
    s.push_str("[modified by rust]");
}

Cargo.toml

[package]
name = "rs-lib-demo"
version = "0.1.0"
edition = "2021"

[lib]
name = "rs_lib_demo"
crate-type = ["cdylib"]

[dependencies]

js代码 app.js

const { equal } = require('assert')
const { load, DataType, open } = require('ffi-rs')

open({
    library: 'rslib',
    path: 'C:\\Code\\Rust\\rs-lib-demo\\target\\release\\rs_lib_demo.dll'
});

const add_ret = load({
    library: 'rslib',
    funcName: 'add',
    retType: DataType.I32,
    paramsType: [DataType.I32, DataType.I32],
    paramsValue: [4, 2]
});
console.log(add_ret);

let str = "Hello, Rust";
load({
    library: 'rslib',
    funcName: 'modify_string',
    retType: DataType.Void,
    paramsType: [DataType.String],
    paramsValue: [str],
    errno: false
});
console.log(str);
console.log('hello');
equal(1, 0);
throw new Error('hello');

运行结果:

C:\Code\nodejs\ffi-demo>node app.js
6

第一个add函数调用正常,结果正常打印,但是调用第二个modify_string函数后,无论是打印还是人为制作异常,都没有效果

zhangyuang commented 5 months ago

String是rust数据类型不是c数据类型,你错误的理解了ffi的含义

wangxiaoyan369 commented 5 months ago

这里用错了是一个问题,但是导致了后续的代码不执行了是另一个问题了

zhangyuang commented 5 months ago

底层内存数据类型错误导致bus error的问题是任意的都有可能发生

wangxiaoyan369 commented 5 months ago

出现了这类错误,能否携带错误信息的提示出来

zhangyuang commented 5 months ago

动态链接库本身不携带symbol的参数签名信息,需要开发者自行保证参数类型的要求与传入一致