【发布时间】:2020-06-30 15:47:54
【问题描述】:
直接使用Node.js可以得到正确的本机内存地址如:
// eg. native dll writen in rust; Of course, this part can be implemented in C or C++ or any others.
#[no_mangle]
pub unsafe extern fn example_concat(
a: *const c_char,
b: *const c_char
) -> *mut c_char
{
let sa = CStr::from_ptr(a).to_str().expect("cannot to_str from a");
let sb = CStr::from_ptr(b).to_str().expect("cannot to_str from b");
let sr = format!("{}{}", sa, sb);
let cr = CString::new(sr).expect("cannot create cr from sr");
println!("[from native lib] cr={} *=0x{:X}", cr.to_str().expect("cannot to_str from cr"), cr.as_ptr() as c_ulonglong);
cr.into_raw()
}
// tester.js
const ffi = require('ffi-napi');
const ref = require('ref-napi');
const str = ref.types.CString;
const lib = ffi.Library( 'lib.dll', { 'example_concat': [ "char *", [ str, str ] ] } );
const buffer = lib.example_concat( "su", "shi" );
console.log( '[from tester.js]', buffer.hexAddress(), buffer.readCString() );
node tester.js 的结果是:
[from native lib] cr=sushi *=0x1E7B3B3E8C0
[from tester.js] 000001E7B3B3E8C0 sushi
这是预期的,没有问题。但是,如果我使用与react-electron 系统类似的 FFI 方法,问题就会发生在我身上。
// App.js in react-electron Node.js project
const remote = window.require('electron').remote;
const ffi = remote.require( 'ffi-napi' );
const ref = remote.require( 'ref-napi' );
const str = ref.types.CString;
const lib = ffi.Library( 'lib.dll', { 'example_concat': [ "char *", [ str, str ] ] } );
const buffer = lib.example_concat( "su", "shi" );
console.log( '[from App.js(electron)]', ref.hexAddress( buffer ), ref.readCString( buffer ) ); // <-- It returns wrong memory address!!
这个电子版的结果是:
[from native lib] cr=sushi *=0x2BFA2F07A10
[from App.js(electron)] 000002BFA3BA7230 sushi
如何使用electron 在项目中获取正确的本机内存地址?
- os = Microsoft Windows 10(64 位)10.0.19041.153
- 节点 = 13.5.0
- node-ffi-napi = 2.4.7
- node-ffi-ref = 1.4.3
- 反应 = 16.13.0
- 电子 = 8.1.1
【问题讨论】:
标签: node.js electron memory-address ffi node-ffi