Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

Mixing C++ and Rust for Fun and Profit: Part 1

Or why switching to Rust is such a large undertaking

// file: main.cpp
#include "rustmodule.h"
// or in an ideal C++ 20 world:
// import rustmodule;

int main()
{
    foo();
    return 0;
}
// file: rustmodule.h
#pragma once

// this is defined in Rust
void foo();
// file: rustmodule.rs
pub fn foo() {
    println!("Hello from Rust");
}
// file: main.cpp
#include "rustmodule.h"
// or in an ideal C++ 20 world:
// import rustmodule;

int main()
{
    foo();
    return 0;
}

// file: rustmodule.h
#pragma once

extern "C" void foo();
// file: rustmodule.rs
#[no_mangle]
pub extern "C" fn foo() {
    println!("Hello from Rust");
}
// file: foo.cpp
#include <iostream>

void bar();
void foo()
{
    std::cout << "Hello from C++\n";
    bar();
}
// file: main.d
import std.stdio;

extern(C++) void foo();
extern(C++) void bar()
{
    writeln("Hello from D");
}

void main()
{
    foo();
}
// file: main.d
import std.stdio;

pragma(mangle, "_ZN10rustmodule3foo17h18576425cfc60609E") void foo();
pragma(mangle, "bar_d_function") void bar()
{
    writeln("Hello from D");
}

void main()
{
    foo();
}
// file: rustmodule.rs
pub fn foo() {
    println!("Hello from Rust");
    unsafe {
        bar();
    }
}
extern {
    #[link_name = "bar_d_function"] fn bar();
}
// file: main.cpp
#include "rustmodule.h"
// or in an ideal C++ 20 world:
// import rustmodule;

int main()
{
    foo();
    return 0;
}

// file: rustmodule.h
#pragma once

// this is in Rust
void foo();
// file: rustmodule.rs
pub fn foo() {
    println!("Hello from Rust");
}
// file: glue.d
@nogc:

// This is the Rust function.
pragma(mangle, "_ZN10rustmodule3foo17h18576425cfc60609E") void foo_from_rust();

// This is exposed to C++ and serves as nothing more than an alias.
extern(C++) void foo()
{
    foo_from_rust();
}

About KDAB


11 Comments

7 - Dec - 2023

Lachu

7 - Dec - 2023

Loren Burkholder

8 - Dec - 2023

Paulo Pinto

8 - Dec - 2023

Loren Burkholder

8 - Dec - 2023

Matheus Catarino

9 - Dec - 2023

Loren Burkholder

16 - Dec - 2023

BitSyndicate

18 - Dec - 2023

Loren Burkholder

17 - Dec - 2023

Andy

17 - Dec - 2023

Marcus

18 - Dec - 2023

Loren Burkholder

01_NoPhoto

Loren Burkholder

Software Engineer

Learn Rust

Learn more

Learn Modern C++

Learn more