Last active
March 25, 2024 18:05
-
-
Save fgalan/885d479c984f7060b7046484d4b5a88d to your computer and use it in GitHub Desktop.
Embeding Rust in C hello world example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
rustc --crate-type=staticlib hello.rs | |
g++ main.cpp -L. -lhello -o main | |
./main |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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