I've been working on a library recently and I want to make C bindings for it. One of the structs in this library returns a slice of trait objects to the user. This is what the function definition looks like:
pub fn controllers(&self) -> &[Box<dyn Controller>] {
&self.controllers
}
I'm not sure how to go about translating this. The C code will not be poking inside these dynamic objects. It will simply be passing them back to rust code, i.e.
pub fn controller_get_name(controller: *const dyn Controller) -> *const c_char {
let controller = controller.as_ref();
controller.get_name().as_ptr();
}
Currently, I have this:
#[no_mangle]
pub extern "C" fn libvibrant_instance_get_controllers(instance: *mut Instance,
mut controllers: *const dyn Controller,
len: *mut usize) {
assert!(!instance.is_null());
assert!(!len.is_null());
let instance = unsafe { instance.as_ref().unwrap() };
controllers = instance.controllers().as_ptr();
unsafe {
*len = instance.controllers().len();
}
}
But obviously, that doesn't work because as_ptr
is returning a *const Box<dyn Controller>
rather than *const dyn Controller
. What can I do here?