Rust structure wrap in C ++ class

I would like to wrap a Rust structure in a C ++ class.

Rust:

#[repr(C)]
pub struct RustStruct {
  num: i32,
  // other members..
}

pub extern "C" fn update(rust_struct: *mut RustStruct) {
  (*rust_struct).num = 1i32;
}

extern "C" {
  void update(void*);
}

C ++:

class Wrapper {
  public:
    Wrapper();
    // ..

  private:
    void* rustStruct;
    // ..
};

Wrapper::Wrapper() {
  update(rustStruct); // crash
}

int main() {
  std::cout << "Testing..";
}

I understand why this will not work. My question is: how can I achieve what I'm basically trying to do (wrap the rust structure in a C ++ class)?

+4
source share
1 answer

There is a combination of several FFI concepts in your answer, so first let me recommend that you read the Link .

There are two ways to achieve the desired result:

  • use POD struct(Plain Old Data) as well as a C-compatible structure
  • use an opaque pointer ( void*in C)

Mixing them, like you, does not make sense.


What to choose?

, .

, : . :

  • Rust ( C ++)

, POD , , Rust.


POD?

, , !

:

#[repr(C)]
pub struct RustStruct {
    num: i32,
    // other members, also PODs!
}

++

struct RustStruct {
    int32_t num;
    // other members, also with Standard Layout
    // http://en.cppreference.com/w/cpp/types/is_standard_layout
};

class Wrapper {
public:
private:
    RustStruct rustStruct;
};

, stricto censu , ++:

class RustStruct {
public:
private:
    int32_t num;
    // other members, also with Standard Layout
    // http://en.cppreference.com/w/cpp/types/is_standard_layout
};

virtual.


?

:

  • Rust //
  • ...

, Rust:

#![feature(box_raw, box_syntax)]
use std::boxed;

pub struct RustStruct {
    num: i32,
    // other members, anything goes
}

pub extern "C" fn createRustStruct() -> *mut RustStruct {
    boxed::into_raw(box RustStruct::new())
}

pub extern "C" fn destroyRustStruct(o: *mut RustStruct) {
    boxed::from_raw(o);
}

... ++:

struct RustStruct;

RustStruct* createRustStruct();
void destroyRustStruct(RustStruct*);

class Wrapper {
public:
    Wrapper(): rustStruct(RustStructPtr(createRustStruct())) {}

private:
    struct Deleter {
        void operator()(RustStruct* rs) const {
            destroyRustStruct(rs);
        }
    };

    typedef std::unique_ptr<RustStruct, Deleter> RustStructPtr;

    RustStructPtr rustStruct;
}; // class Wrapper

, , , Wrapper ( Rust). , !

. , ++, copy/destroy , .

+9

All Articles