本文介绍了创建链接到Rust dylib的共享C对象,以在R中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我试图创建一个共享对象,我可以加载到R,通过R的C API调用Rust函数。要从C调用Rust,我要遵循此博文。我的问题出现,当我尝试创建共享库和链接到Rust库。链接器抱怨,它找不到我的Rust功能。我对编译语言很新鲜,并且在转向SO之前给了这个几天的努力。在那个时候,我已经学到了很多关于编译器标志,但是没有更接近解决方案。我认为这可能是显而易见的。I am trying to create a shared object I can load into R that calls Rust functions by way of R's C API. To call Rust from C, I am following this blog post. My problem arises when I try to create the shared library and link to the Rust library. The linker complains that it can't find my Rust function. I am quite new to compiled languages and have given this a couple days' worth of effort before turning to SO. In that time I have learned a lot about compiler flags and yet come no closer to a solution. I think it may be something obvious.我的C ++代码:#include "Rinternals.h"#include "R.h"#include "treble.h"// test.cppextern "C" {SEXP triple(SEXP val) { int32_t ival = *INTEGER(val); Rprintf("9 tripled is %d\n", treble(ival)); return R_NilValue;}} treble.h:#include <stdint.h>int32_t treble(int32_t value);我的Rust代码:#![crate_type = "dylib"]#[no_mangle]pub extern fn treble(value: i32) -> i32 { value * 3}在命令行上:$ rustc glue.rs$ g++ -shared test.cpp -o test.so -I/Library/Frameworks/R.framework/Headers -L/Library/Frameworks/R.framework/Libraries -L. -lR -lglueUndefined symbols for architecture x86_64: "treble(int)", referenced from: _triple in test-dac64b.old: symbol(s) not found for architecture x86_64clang: error: linker command failed with exit code 1 (use -v to see invocation)检查生成的对象文件:$ nm -gU libglue.dylib...0000000000001750 T _treble推荐答案 C ++代码,你需要声明Rust函数(可以通过C ABI获得) externC。In the C++ code, you need to declare the Rust function (which is available via the C ABI) as extern "C". treble.h#include <stdint.h>extern "C" { int32_t treble(int32_t value);}您得到的错误是因为C ++编译器名称mangling treble 之前尝试链接到它。 externC禁用修改。The error you are getting is because the C++ compiler is name mangling the method treble before attempting to link against it. extern "C" disables the mangling.此外,您的Rust FFI代码应始终使用 libc crate ;在你的情况下,你想要 libc :: int32_t 。Additionally, your Rust FFI code should always use the types from the libc crate; in your case you want libc::int32_t. 这篇关于创建链接到Rust dylib的共享C对象,以在R中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-23 06:29