Using c++ class in rust

Hi, I have a question. I am trying to use a c++ class in rust using the autocxx crate and pass it as a parameter when calling a dll.

Please see the code below

B.h

#pragma once
#include <vector>
#include <string>

class A {
public:
    A() {};
    std::string name;
    std::string address;
};

class B {
public:
    B() {};
    int age;
    std::vector<A> a_list;
};

rust main.rs

use autocxx::prelude::*;
use libloading::{Library, Symbol};

include_cpp! {
    #include "B.h"
    safety!(unsafe_ffi)
    generate!("A")
    generate!("B")
}

fn main() {
    unsafe {
        let lib = Library::new("C:/Users/wjkim2/source/repos/test_dll/x64/Debug/test_dll.dll").expect("Failed to load");

        let class_test: Symbol<unsafe extern "C" fn(*mut ffi::B)> = lib.get(b"BTestFunc").expect("faile to get");

        let mut b = ffi::B::new().within_unique_ptr();

        class_test(b.as_mut_ptr());
    }
}

test_dll BTestFunc

extern "C" _declspec(dllexport) void BTestFunc(B* b)
{
    MessageBox(NULL, L"success", L"Hello", MB_OK);
    A a1 = A();
	a1.name = "wangki";
	a1.address = "Seoul";

    A a2 = A();
    a2.name = "kyu";
    a2.address = "yongin";

	b->a_list.push_back(a1);
	b->a_list.push_back(a2);

	MessageBox(NULL, L"success", L"Hello", MB_OK);
}

A STATUS_ACCESS_VIOLATION error occurs.

error: process didn't exit successfully: `target\debug\autocxx_test.exe` (exit code: 0xc0000005, STATUS_ACCESS_VIOLATION)

How can I implement the method of passing a class object as a parameter like above?

Is it because the memory layout is different?? I haven't been able to solve it for several days. Please help me, bro.

Thank you.

I don't remember for sure, but I think the _declspec(dllexport) attribute uses __stdcall convention, which should correspond to unsafe extern "system" fn(*mut ffi::B) in rust, which is windows-msvc specific.

1 Like