Skip to content

Instantly share code, notes, and snippets.

@fgalan
Last active March 25, 2024 18:05
Show Gist options
  • Save fgalan/885d479c984f7060b7046484d4b5a88d to your computer and use it in GitHub Desktop.
Save fgalan/885d479c984f7060b7046484d4b5a88d to your computer and use it in GitHub Desktop.
Embeding Rust in C hello world example
rustc --crate-type=staticlib hello.rs
g++ main.cpp -L. -lhello -o main
./main
// hello.rs
use std::ffi::CStr;
use std::os::raw::c_char;
#[no_mangle]
pub extern "C" fn hello_from_rust(name: *const c_char) {
// Safety: We need to ensure that the input pointer is not null and points to valid C string data
if !name.is_null() {
// Convert the raw C string pointer to a safe Rust string slice
let name_str = unsafe { CStr::from_ptr(name) };
// Convert the Rust string slice to a UTF-8 string and print it
if let Ok(name) = name_str.to_str() {
println!("Hello, {}!", name);
} else {
eprintln!("Invalid UTF-8 sequence in input string");
}
} else {
eprintln!("Null pointer passed as input");
}
}
// main.cpp
#include <iostream>
extern "C" {
void hello_from_rust(const char* str);
}
int main() {
hello_from_rust("my friend");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment