问题描述
我想生成6个随机数,将它们推到一个向量上,然后使用rustc_serialize
将该向量编码为JSON字符串,供NodeJS使用.
I want to generate 6 random numbers, push them onto a vector, then use rustc_serialize
to encode that vector as a JSON string to be consumed by NodeJS.
extern crate rand;
extern crate rustc_serialize;
use rand::{OsRng, Rng};
use rustc_serialize::json::{self, Json, ToJson};
#[no_mangle]
pub extern "C" fn generate() -> String {
let choices: [u8; 6] = [1, 2, 3, 4, 5, 6];
let mut rand_vec: Vec<u8> = Vec::new();
let mut rng = match OsRng::new() {
Ok(t) => t,
Err(e) => panic!("Failed to create OsRng!, {}", e),
};
for _ in 0..5 {
rand_vec.push(*rng.choose(&choices).unwrap());
}
json::encode(&rand_vec).unwrap()
}
此代码被编译为库generate_6_rand.dll
.我有一个单独的二进制文件用于测试此代码.
This code is compiled as a library generate_6_rand.dll
. I have a separate binary file that I'm using to test this code.
如果我运行
println!("{:?}", &json::encode(&rand_vec).unwrap());
输出:
"[5,4,3,4,1,3]" //as expected
然后我在NodeJS程序中使用.dll
:
I then use my .dll
in a NodeJS program:
var ffi = require('ffi');
var path = require('path');
var lib = ffi.Library(path.join(__dirname,
'./ffi/generate_6_rand.dll'), {
generate: [ 'string', [ ]]
});
console.log(lib.generate());
测试
console.log(lib.generate())
输出:
��.�
它是EcmaScript ArrayBuffer
吗?
console.log(new ArrayBuffer(lib.generate())
Is it an EcmaScript ArrayBuffer
?
console.log(new ArrayBuffer(lib.generate())
输出:
ArrayBuffer { byteLength: 0 }
它的原始链属性是什么?
console.log(lib.generate().__proto__)
What are it's proto chain properties?
console.log(lib.generate().__proto__)
输出:
[String: '']
将代码更改为:
var ref = require('ref');
var ArrayType = require('ref-array');
var Int32Array = ArrayType(ref.types.int32);
var lib = ffi.Library(path.join(__dirname,
'../dice_lib/target/release/generate_6_rand.dll'), {
generate: [ Int32Array, [ ]]
});
console.log(new ArrayBuffer(lib.generate()));
输出:
ArrayBuffer { byteLength: 0 }
为什么FFI函数不返回我期望的JSON字符串?
Why does the FFI function not return a JSON string as I'm expecting?
推荐答案
谢谢韦斯利·怀瑟(Wesley Wiser)为我提供了有关CString
的重要线索.我在 Rust FFI Omnibus 中找到了答案.
Thank you Wesley Wiser for giving me a big clue with CString
. I found the answer in The Rust FFI Omnibus.
无论我返回JSON字符串还是返回CString
,在我的NodeJS程序访问它之前,都已释放了用于我期望的JSON字符串的内存.
The memory for my expected JSON string was being deallocated before my NodeJS program could access it, whether I returned the JSON string or returned a CString
.
这是基于该文章的我的解决方案. 对于其他新手程序员,请记住,我的解决方案可能不理想:
Here's my solution based on that article. To other novice programmers, please keep in mind that my solution may or may not be ideal:
extern crate rand;
extern crate rustc_serialize;
extern crate libc;
use libc::c_char;
use rand::{OsRng, Rng};
use std::ffi::CString;
use rustc_serialize::json;
#[no_mangle]
pub extern "C" fn generate() -> *mut c_char {
let choices: [u8; 6] = [1, 2, 3, 4, 5, 6];
let mut rand_vec: Vec<u8> = Vec::new();
let mut rng = match OsRng::new() {
Ok(t) => t,
Err(e) => panic!("Failed to create OsRng!, {}", e),
};
for _ in 0..6 {
rand_vec.push(*rng.choose(&choices).unwrap());
}
let json_string = CString::new(json::encode(&rand_vec).unwrap()).unwrap();
json_string.into_raw()
}
#[no_mangle]
pub extern "C" fn free_memory(pointer: *mut c_char) {
unsafe {
if pointer.is_null() {
return;
}
CString::from_raw(pointer)
};
}
NodeJS
var ffi = require('ffi');
var path = require('path');
var lib = ffi.Library(path.join(__dirname,
'./ffi/generate_6_rand.dll'), {
generate: [ 'char *' , [ ]],
free_memory: ['void', ['char *']]
});
var json_string = lib.generate();
var save_json = JSON.parse(json_string.readCString());
console.log( json_string.readCString()); // Output: [6,1,6,4,1,4]
lib.free_memory(json_string);
console.log(json_string.readCString()); // Output: ��x�
我设置了两个console.log
来显示释放之前和之后的输出.
I set up two console.log
s to show what the output before and after deallocation.
这篇关于如何从NodeJS中的Rust FFI函数返回字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!