Skip to content

Instantly share code, notes, and snippets.

@hempnall
Created December 7, 2017 20:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hempnall/db3e6eb6d0f3dabbf8d133caf0991dbe to your computer and use it in GitHub Desktop.
Save hempnall/db3e6eb6d0f3dabbf8d133caf0991dbe to your computer and use it in GitHub Desktop.
Calling C++ code from Rust

Start off with some Rust source code

hw.rs :

#[link(name = "extern")]
extern {
	fn hello();
}


fn hw_from_a_fn() {
	println!("Hello World! (from a function)");
}

fn main() {
    // The statements here will be executed when the compiled binary is called

    // Print text to the console
    println!("Hello World!");
    hw_from_a_fn();
	
unsafe {
    hello();
}
}

And some C++ code :

#include <stdio.h>

extern "C" {

void hello() {
    printf("Hello, World!\n");
}

}

Compile the C++ code into a static archive:

$ g++ -c extern.cpp
$ ar rvs libextern.a extern.o

Now compile your Rust-to-C++ program

$ rustc -L . hw.rs

... and run your program ...

$ ./hw
Hello World!
Hello World! (from a function)
Hello, World!
$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment