mystor / rust-cpp

Embed C++ directly inside your rust code!
Apache License 2.0
795 stars 44 forks source link

Example of passing own class to Rust lambda #75

Closed ea2973929 closed 4 years ago

ea2973929 commented 4 years ago

The following code (although I stripped a lot of details) fails to build with:

expectedas',

cpp!(unsafe [myclass: const* std::ffi::c_void as "IMyClass*"]{
       myclass->CallMyMethod();
});

What is the correct way to pass my a pointer to an object from rust to c++ and calling a method on the object?

ogoffart commented 4 years ago

I have not tried, but i suspect the probltm is because const* -> *const

So maybe

cpp!(unsafe [myclass: *const std::ffi::c_void as "const IMyClass*"]{
       myclass->CallMyMethod();
});
ea2973929 commented 4 years ago

Oh, sorry about that typo. Flipping it around still generates the error however.

cpp!(unsafe [myclass: *const std::ffi::c_void as "const IMyClass*"]{
       myclass->CallMyMethod();
});
ea2973929 commented 4 years ago

I've found the error. In the lambda capture the type should be omitted. I guess that's deduced.

let my_class: *const std::ffi::c_void = // retrieve that somehow
cpp!(unsafe [myclass as "const IMyClass*"]{
       myclass->CallMyMethod();
});

works fine

benkay86 commented 4 years ago

You can't cast myclass to a different type within the cpp! macro. In the example you gave it is implied that myclass is already a pointer, in which case you can safely omit the cast to c_void.

fn call_my_method(myclass: *const MyClass)
{
    cpp!(unsafe [myclass as "const IMyClass*"]{
        myclass->CallMyMethod();
    });
}