Create a generic C object associated with Rust dylib for use in R

I am trying to create a generic object that I can load into R that calls Rust functions through the RC API. To call Rust from C, I follow this blog post . My problem arises when I try to create a shared library and reference the Rust library. The compiler complains that it cannot find my Rust function. I am completely new to compiled languages ​​and gave this a couple of days of effort before turning to SO. During this time, I learned a lot about the flags of the compiler and yet I am not getting closer to the solution. I think this may be something obvious.

My C ++ code:

#include "Rinternals.h" #include "Rh" #include "treble.h" // test.cpp extern "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); 

My rust code:

 #![crate_type = "dylib"] #[no_mangle] pub extern fn treble(value: i32) -> i32 { value * 3 } 

This is what I do on the command line:

 $ rustc glue.rs $ g++ -shared test.cpp -o test.so -I/Library/Frameworks/R.framework/Headers -L/Library/Frameworks/R.framework/Libraries -L. -lR -lglue Undefined symbols for architecture x86_64: "treble(int)", referenced from: _triple in test-dac64b.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) 

Checking the file of the object that creates rust:

 $ nm -gU libglue.dylib ... 0000000000001750 T _treble 
+3
c ++ c r rust ffi
source share
1 answer

In C ++ code, you need to declare a Rust function (which is accessible through C ABI) as extern "C" .

treble.h

 #include <stdint.h> extern "C" { int32_t treble(int32_t value); } 

The error you get is that the C ++ compiler is the name that controls the treble method before trying to bind it. extern "C" disables mangling.

Also, your Rust RFI code should always use types from libc crate ; in your case you want libc::int32_t .

+3
source share

All Articles