has updated because of some suggestions
System:macOS 10.14.6
The question I want to ask here is how do I use rust to call a compiled .so file, sorry, I am new to this part.
I have a very simple c file:
#include "add.h"
int add(int a, int b) {
return a + b;
}
Then I used gcc-fPIC -shared -o libadd.so add.c
to compile it into a .so file and put it in the lib directory
Then I wrote this in rust's build.rs file:
use std::env;
use std::path::{Path};
fn main() {
let pwd_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let path = Path::new(&*pwd_dir).join("lib");
println!("cargo:rustc-link-search=native={}", path.to_str().unwrap());
println!("cargo:rustc-link-lib=dylib=add");
// println!("cargo:rustc-link-lib=static=add");
// println!("cargo:rerun-if-changed=src/hello.c");
}
I expect I can get and use this function, main.rs is:
extern { fn add(a: i32, b: i32) -> i32; }
fn main() {
let c = unsafe { let d = add(3, 5); d };
println!("c: {:?}", c);
}
cargo build
is ok, but cargo run
with error:
Compiling hello-from-generated-code-3 v0.1.0 (/Users/niexiaotao/work/rust-server/rust-ffi/hello-from-generated-code-3)
Finished dev [unoptimized + debuginfo] target(s) in 0.34s
Running `target/debug/hello-from-generated-code-3`
dyld: Library not loaded: libadd.so
Referenced from: /Users/niexiaotao/work/rust-server/rust-ffi/hello-from-generated-code-3/target/debug/hello-from-generated-code-3
Reason: image not found
[1] 81811 abort cargo run
other thing: I change the .so to .a and cargo run is ok.
Sample code here
Thank you for your help!