如果我直接使用Node.js
,我可以得到正确的 native 内存地址,例如:
// 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
可以预料,没有问题。但是,如果我将类似的FFI方法与
react-electron
系统一起使用,问题就会发生在我身上。// 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!!
该 Electron 版本的结果是:
[from native lib] cr=sushi *=0x2BFA2F07A10
[from App.js(electron)] 000002BFA3BA7230 sushi
如何使用
electron
在项目中获取正确的 native 内存地址?最佳答案
我得到了这种情况的答案。在发布的情况下,我使用了nodeIntegration: true
,然后使用const remote = window.require('electron').remote
和remote.require
功能实现了该示例。然后,通过AddressForArgs
的ref.HexAddress
(†1)可能返回基于 Electron 客户端的地址(我现在不知道node-ref-napi,node-ffi-napi和 Electron 的更多内部信息)。
因此,我尝试使用nodeIntegration: false
功能更改preload
设置。
// preload.js
window.ffi = require( 'ffi-napi' );
window.ref = require( 'ref-napi' );
// App.js ( Fixed to the preload feature based )
// const remote = window.require('electron').remote;
const ffi = window.ffi; //remote.require( 'ffi-napi' );
const ref = window.ref; //remote.require( 'ref-napi' );
然后,它可以正常工作!干得好,恭喜我!!
(†1):https://github.com/node-ffi-napi/ref-napi/blob/ed19a20370394b0b1914566f4ea9b5354b475732/src/binding.cc#L72
关于node.js - 如何在 Electron + Node -ffi-napi中获得正确的 native 内存地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60758366/