Jump to content

Cara binding C++ dan Rust

From Haidhi Wiki
Revision as of 07:16, 12 March 2026 by SanzSkuy (talk | contribs) (Created page with "Buat project rust <syntaxhighlight lang=bash> cargo new --lib rust_code </syntaxhighlight> Cargo.toml <syntaxhighlight lang=toml> [package] name = "rust_code" version = "0.1.0" edition = "2024" [dependencies] [lib] crate-type = ["staticlib"] </syntaxhighlight> lalu contoh <code>src/lib.rs</code> <syntaxhighlight lang=rust> #[unsafe(no_mangle)] pub extern "C" fn hello_from_rust() { println!("Hello from Rust"); } #[unsafe(no_mangle)] pub extern "C" fn add_number(a...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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