书中的FFI示例无法在Windows

时间:2015-05-30 12:06:34

标签: windows rust

external c dll with call back example后链接出错。

我创建了anneclib.dll并将其分散(并且lib)甚至尝试了完整路径但仍然得到相同的错误(但是使用完整路径)。

  

错误1错误:与gcc链接失败:退出代码:1注意:“gcc”   “-Wl, - enable-long-section-names”“ - fno-use-linker-plugin”   “-Wl, - nxcompat”“ - static-libgcc”“ - m64”“ - L”“C:\ Program Files \ Rust   稳定1.0 \ bin \ rustlib \ x86_64-pc-windows-gnu \ lib“” - o“   “obj \ Debug \ Anne.exe”“obj \ Debug \ Anne.o”“ - Wl, - gc-sections”   “C:\ Program Files \ Rust stable   1.0 \ bin \ rustlib \ x86_64-pc-windows-gnu \ lib \ libstd-4e7c5e5c.rlib“”C:\ Program Files \ Rust stable   1.0 \ BIN \ rustlib \ x86_64的-PC-Windows的GNU \ LIB \ libcollections-4e7c5e5c.rlib”   “C:\ Program Files \ Rust stable   1.0 \ bin \ rustlib \ x86_64-pc-windows-gnu \ lib \ libunicode-4e7c5e5c.rlib“”C:\ Program Files \ Rust stable   1.0 \ bin \ rustlib \ x86_64-pc-windows-gnu \ lib \ librand-4e7c5e5c.rlib“”C:\ Program Files \ Rust stable   1.0 \ bin \ rustlib \ x86_64-pc-windows-gnu \ lib \ liballoc-4e7c5e5c.rlib“”C:\ Program Files \ Rust stable   1.0 \ bin \ rustlib \ x86_64-pc-windows-gnu \ lib \ liblibc-4e7c5e5c.rlib“”C:\ Program Files \ Rust stable   1.0 \ bin \ rustlib \ x86_64-pc-windows-gnu \ lib \ libcore-4e7c5e5c.rlib“” - L“”C:\ Program Files \ Rust stable   1.0 \ bin \ rustlib \ x86_64-pc-windows-gnu \ lib“” - L“”C:\ src \ ann \ anne.rust \ anne.rust \ Anne.rust \ bin \ x86_64-pc-windows-gnu“   “-L”“C:\ src \ ann \ anne.rust \ anne.rust \ Anne \ bin \ x86_64-pc-windows-gnu”   “-Wl, - whole-archive”“-Wl,-Bstatic”“-Wl, - no-whole-archive”   “-Wl,-Bdynamic”“ - lanneclib”“ - lws2_32”“ - luserenv”“ - lcompiler-rt”   注意:ld:找不到-lanneclib

使用Visual Studio Rust项目。

我应该把它放在哪里?

extern fn callback(a: i32) {
    println!("I'm called from C with value {0}", a);
}

#[link(name = "anneclib")]
extern {
   fn register_callback(cb: extern fn(i32)) -> i32;
   fn trigger_callback();
}

fn main() {
    unsafe {
        register_callback(callback);
        trigger_callback(); // Triggers the callback
    }
}

1 个答案:

答案 0 :(得分:3)

在错误消息中,您可以看到文件夹[your source folder]\bin\x86_64-pc-windows-gnu已添加到库路径中。您必须将您的库放入此文件夹。您可能还需要在库名称中添加“lib”前缀。

这是一个适合我的小例子:

带有hello-function的C文件:

#include <stdio.h>

void hello() {
    printf("Hello from C!\n");
}

使用MinGW将C文件编译为共享库libhello.c:

gcc -shared -o libhello.dll hello.c

Rust文件main.rs:

#[link(name = "hello")]
extern {
    fn hello();
}

fn main() {
    unsafe { hello(); }
}

现在你必须将(一份)libhello.dll放入子文件夹\ bin \ x86_64-pc-windows-gnu:

+ bin
+ --- x86_64-pc-windows-gnu
      + --- libhello.dll
+ main.rs

你应该可以通过

编译它
rustc main.rs

注意,为了执行main.exe,您还需要main.exe旁边或系统路径中的libhello.dll副本。