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 2

Of structs and strings

// file: cppmodule.cpp
#include <iostream>
#include <cstdint>

struct Foo
{
    int32_t foo;
    int32_t bar;
    bool baz;
};

void foobar(Foo foo)
{
    std::cout << "foo: " << foo.foo
              << ", bar: " << foo.bar
              << ", baz: " << foo.baz
              << '\n';
}
extern {
    #[link_name = "_Z6foobar3Foo"] pub fn foobar(foo: Foo);
}

#[repr(C)]
pub struct Foo {
    pub foo: i32,
    pub bar: i32,
    pub baz: bool,
}

fn main() {
    let f = Foo{foo: 0, bar: 42, baz: true};
    unsafe {
        foobar(f);
    }
}
// file: links.cpp
#include <string>

std::string getLink()
{
    return "https://kdab.com";
}
// file: main.rs
mod links;

fn main() {
    println!("{} is the best website!", links::getLink());
}
// wrapper file: links.rs
extern {
    #[link_name = "_Z7getLinkB5cxx11v"]
    pub fn getLink() -> String; // ???
}
// wrapper file: links_stringwrapping.cpp
#include "links.h" // assuming we made a header file for links.cpp above

#include <cstring>

const char *getLink_return_cstyle_string()
{
    // we need to call strdup to avoid returning a temporary object
    return strdup(getLink().c_str());
}
// wrapper file: links.rs
#![crate_type = "staticlib"]

use std::ffi::CStr;
use std::os::raw::c_char;
use std::alloc::{dealloc, Layout};

extern {
    #[link_name = "_Z28getLink_return_cstyle_stringv"]
    fn getLink_return_cstyle_string() -> *const c_char;
}

pub fn getLink() -> String {

    let cpp_string = unsafe { getLink_return_cstyle_string() };
    let rust_string = unsafe { CStr::from_ptr(cpp_string) }
        .to_str()
        .expect("This had better work...")
        .to_string();
    // Note that since we strdup'ed the temporary string in C++, we have to manually free it here!
    unsafe { dealloc(cpp_string as *mut u8, Layout::new::()); }
    return rust_string;
}

About KDAB


01_NoPhoto

Loren Burkholder

Software Engineer

Learn Rust

Learn more

Learn Modern C++

Learn more