从Julia调用Rust函数,就像ccall一样
在alexcrichton/rust-ffi-examples repo中有一个例子:
Cargo.toml:
[package]
name = "julia-to-rust"
version = "0.1.0"
authors = ["timmonfette1 <monfette.timothy@gmail.com>"]
[lib]
name = "double_input"
crate-type = ["dylib"]
Run Code Online (Sandbox Code Playgroud)
src/lib.rs:
#[no_mangle]
pub extern fn double_input(input: i32) -> i32 {
input * 2
}
Run Code Online (Sandbox Code Playgroud)
src/main.jl:
input = Int32(10)
output = ccall((:double_input, "target/debug/libdouble_input"),
Int32, (Int32,), input)
print(input)
print(" * 2 = ")
println(output)
Run Code Online (Sandbox Code Playgroud)
Makefile:
ifeq ($(shell uname),Darwin)
EXT := dylib
else
EXT := so
endif
all: target/debug/libdouble_input.$(EXT)
julia src/main.jl
target/debug/libdouble_input.$(EXT): src/lib.rs Cargo.toml
cargo build
clean:
rm -rf target
Run Code Online (Sandbox Code Playgroud)
我们的想法是导出一个非破坏函数并将您的生锈库编译为普通的本机共享库.然后你只使用朱莉娅的标准C FFI.
从Rust那里召唤朱莉娅
我想最好使用juliacrate - 它提供了一个原始C API的安全包装.回购示例:
fn main() {
use julia::api::{Julia, Value};
let mut jl = Julia::new().unwrap();
jl.eval_string("println(\"Hello, Julia!\")").unwrap();
// Hello, Julia!
let sqrt = jl.base().function("sqrt").unwrap();
let boxed_x = Value::from(1337.0);
let boxed_sqrt_x = sqrt.call1(&boxed_x).unwrap();
let sqrt_x = f64::try_from(boxed_sqrt_x).unwrap();
println!("{}", sqrt_x);
// 36.565010597564445
}
Run Code Online (Sandbox Code Playgroud)