ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-linux]
rustc 0.13.0-nightly (f168c12c5 2014-10-25 20:57:10 +0000)

我想将ffi gem与rust结合使用。

我已阅读this(已过时)博客文章,其中显示了如何执行此操作。

问题是:它不起作用。

这是我的代码:

test.rs:
fn test(bla: i32) -> i32 { bla*bla }

#[no_mangle]
extern fn _test_wrapper(i: i32) -> i32 {
  test(i)
}

test.rb:
require 'ffi'

module Test
  extend FFI::Library
  ffi_lib File.absolute_path 'libtest.so'

  attach_function :_test_wrapper, [:int32], :int32
end

我这样编译test.rs:
rustc --crate-type dylib test.rs

接着
ruby test.rb

输出:
/home/me/.rvm/gems/ruby-2.1.2/gems/ffi-1.9.6/lib/ffi/library.rb:261:in `attach_function': Function '_test_wrapper' not found in [/home/me/Dokumente/ruby/rust_require/specs/test/libtest.so] (FFI::NotFoundError)
    from test.rb:7:in `<module:Test>'
    from test.rb:3:in `<main>'

我做错了什么? (我已经尝试过将其设置为pub extern fn ...,也不起作用。)

最佳答案

亲近了,您只需要解决编译Rust代码并使函数公开时收到的警告:

#[no_mangle]
pub extern fn _test_wrapper(i: i32) -> i32 {
  test(i)
}

为了帮助我调试问题,我使用了nm来查看已编译的库导出了哪些符号。我在OS X上,因此您可能需要调整参数和文件名:
$ nm -g libtest.dylib
0000000000000e30 T __test_wrapper
0000000000001020 S _rust_metadata_test_04c178c971a6f904
                 U _rust_stack_exhausted
                 U dyld_stub_binder

在将该功能标记为公共(public)功能之前,该功能未显示在此列表中。

10-05 20:32
查看更多