Cara binding C++ dan Rust
Appearance
Buat project rust
cargo new --lib rust_code
Cargo.toml
[package]
name = "rust_code"
version = "0.1.0"
edition = "2024"
[dependencies]
[lib]
crate-type = ["staticlib"]
lalu contoh src/lib.rs
#[unsafe(no_mangle)]
pub extern "C" fn hello_from_rust() {
println!("Hello from Rust");
}
#[unsafe(no_mangle)]
pub extern "C" fn add_number(a: i32, b: i32) -> i32 {
a + b
}
lalu di luar project Rust, code C++
#include <iostream>
extern "C" {
void hello_from_rust();
int add_number(int a, int b);
}
int main() {
std::cout << "C++ code is running" << std::endl;
hello_from_rust();
int result = add_number(10, 5);
std::cout << "Rust add_number result " << result << std::endl;
return 0;
}
Cara compile dan run
Buat Makefile, isinya kayak gini:
.PHONY: compile_rust compile run
compile_rust:
cd rust_code && cargo build --release
compile: compile_rust
g++ main.cpp -o app -L./rust_code/target/release -lrust_code -lpthread -ldl -lrt
run: compile
./app
lalu run dengan ketik make run