我一直试图在
https://github.com/shadowmint/rust-dl-example这里使用cmake和rust来获得一个基本的概念证明并运行,但无济于事.
基本思想是构建一个DLL,然后像这样加载符号:
let dl = DynamicLibrary::open(Some(dl_path));
match dl {
Ok(dll) => {
// Try loading symbols. Note that because of the api we can't
// directly pass T as fn(c_int) -> c_int, because the return is
// a pointer, not a pointer to a pointer.
unsafe{
rtn.foo = match dll.symbol::<c_void>("foo") {
Ok(symbol) => Some(transmute(symbol)),
Err(_) => None
};
rtn.bar = match dll.symbol::<c_void>("bar") {
Ok(symbol) => Some(transmute(symbol)),
Err(_) => None
};
trace!("Read: {}", dll.symbol::<c_void>("foo"));
trace!("Read: {}", dll.symbol::<c_void>("bar"));
rtn.lib = Some(dll);
}
}
哪个在linux和osx上有魅力,但遗憾的是在Windows上失败了:
Compiling dltest v0.1.0 (file:///C:/projects/rust-all/rust-dl-example)
Running target\dltest-3ed01b3dac66913e.exe
running 1 test
Pattern: Some(C:\projects\rust-all\rust-dl-example\build\*foo*.dll)
Some(C:\projects\rust-all\rust-dl-example\build\libfoo.dll)
Read: Err(Error code 127)
Read: Err(Error code 127)
Successfully loaded table
Done1
Done2
stack backtrace:
1: 0x5452c8 - main
2: 0x549525 - main
3: 0x54effd - main
4: 0x54ecc2 - main
5: 0x4d8e8d - main
6: 0x402411
7: 0x4023e3
8: 0x40238d
9: 0x40ccbc
10: 0x43d438 - main
11: 0x52e277 - main
12: 0x54d4cc - main
13: 0x54fc0f - main
14: 0x54fbe9 - main
15: 0x54d55e - main
16: 0x54d309 - main
17: 0x54d116 - main
18: 0x54e64d - main
19: 0x76fc652d - BaseThreadInitThunk
task failed during unwinding. aborting.
错误代码127是’找不到符号’的魔术,但首先它没有正确返回错误,其次,我看不到我的DLL有什么问题.它在c程序中工作正常……它没有任何奇怪的联系:
这是怎么回事?任何人都有一个带有windows&的DLL的工作示例锈?
最佳答案 我的猜测是你没有正确匹配你的DLL的
calling convention.我用这段代码创建了一个DLL:
#[no_mangle]
// Note explicit calling convention
pub extern "C" fn foo_add_2(a: u32) -> u32 {
a + 2
}
编译为:
rustc --crate-type=dylib
并将其作为:
use std::dynamic_lib::DynamicLibrary;
use std::mem::transmute;
fn main() {
let lib = match DynamicLibrary::open(Some("lib")) {
Ok(x) => x,
Err(x) => panic!("{}", x),
};
// Note explicit calling convention
let meth: extern "C" fn(u32) -> u32 = unsafe {
match lib.symbol::<u8>("foo_add_2") {
Ok(x) => transmute(x),
Err(x) => panic!("{}", x),
}
};
let input = 5;
let res = meth(input);
println!("Hello, library! ({} + 2 => {})", input, res);
}
这在2014-12-08的Windows 7和Rust夜间32位虚拟机上运行良好.
但是,如果我将调用约定更改为不匹配,或者将其关闭,我会看到您的错误127.