cxx icon indicating copy to clipboard operation
cxx copied to clipboard

C++ structs with constructors

Open notdanilo opened this issue 4 years ago • 0 comments

Hi! I am trying to interface these two codes, but I am getting a segmentation fault when I introduce constructors on the C++ side. I am on Windows, using msvc.

I am interested in

  1. use the knowledge of this project to understand what might be causing this in this code,
  2. how to fix the code as it is and
  3. how I can make use of cxx to solve this issue.
#[repr(C)]
pub struct FVector2D {
    pub x: f32,
    pub y: f32
}

#[no_mangle]
pub extern "C" fn rust(a: FVector2D, b: FVector2D) -> FVector2D {
    FVector2D { x: a.x + b.x, y: a.y + b.y }
}

and

#include <windows.h>
#include <iostream>

// Works without this.
#define CONSTRUCTORS

struct FVector2D {
    float X;
    float Y;
    #ifdef CONSTRUCTORS
    FVector2D(float X, float Y): X(X), Y(Y) {}
    FVector2D(const FVector2D& from): FVector2D(from.X, from.Y) {}
    #endif
};

typedef FVector2D (*Function)(FVector2D, FVector2D);

int main(int argc, char **argv) {
    auto library = LoadLibrary("C:/Users/dangu/dev/revu-design/rust-ue/target/debug/rust_ue.dll");
    std::cout << "Library: " << library << std::endl;
    if (library) {
        auto function = (Function) GetProcAddress(library, "rust");
        std::cout << "Function: " << function << std::endl;
        if (function) {
            #ifdef CONSTRUCTORS
            FVector2D a(1.0, 2.0);
            FVector2D b(3.0, 4.0);
            #else
            FVector2D a = { 1.0, 2.0 };
            FVector2D b = { 3.0, 4.0 };
            #endif

            auto result = function(a, b); // segmentation fault! :(
            std::cout << result.X << " " << result.Y << std::endl;
        }
    }
    return 0;
}

notdanilo avatar Aug 26 '21 17:08 notdanilo