crustffirust-bindgen

How to properly wrap a C function pointer in Rust?


I have a C struct Foo with a function pointer. In my Rust bindings, I would like to allow users to set this function pointer, but I would like to avoid users having to deal with FFI types.

foo.h

struct Foo {
  void*   internal;
  uint8_t a;
  void (*cb_mutate_a)(void*);
};

struct Foo* foo_new();
void        foo_free(struct Foo* foo);
void        foo_call(struct Foo* foo);

foo.c

struct Foo* foo_new() {
  return calloc(1, sizeof(struct Foo));
}

void foo_free(struct Foo* foo) {
  free(foo);
}

void foo_call(struct Foo* foo) {
  return foo->cb_mutate_a(foo->internal);
}

My current solution is to create a Rust struct Bar which has a pointer to the bindgen-generated C struct foo_sys::Foo, and in it I have a trait object (rust_cb) that is the actual callback I would like to expose in the Rust API. I set the C cb to point to a wrapped_cb and set the internal pointer to point to Bar, this way I am able to call rust_cb from inside wrapped_cb.

This code works but complains about access to uninitialised memory. When I run it with Valgrind, I see invalid reads at the point where I access the (*bar).rust_cb inside wrapped_cb. I am not sure what I am doing wrong.

extern crate libc;

use std::ffi;

#[repr(C)]
#[derive(Debug, Copy)]
pub struct Foo {
    pub internal: *mut libc::c_void,
    pub a: u8,
    pub cb_mutate_a: ::core::option::Option<unsafe extern "C" fn(arg1: *mut libc::c_void)>,
}

impl Clone for Foo {
    fn clone(&self) -> Self {
        *self
    }
}

extern "C" {
    pub fn foo_new() -> *mut Foo;
}
extern "C" {
    pub fn foo_free(foo: *mut Foo);
}
extern "C" {
    pub fn foo_call(foo: *mut Foo);
}

struct Bar {
    ptr: *mut Foo,
    rust_cb: Option<Box<dyn FnMut(&mut u8)>>,
}

impl Bar {
    fn new() -> Bar {
        unsafe {
            let mut bar = Bar {
                ptr: foo_new(),
                rust_cb: Some(Box::new(rust_cb)),
            };
            (*bar.ptr).cb_mutate_a = Some(cb);
            let bar_ptr: *mut ffi::c_void = &mut bar as *mut _ as *mut ffi::c_void;
            (*bar.ptr).internal = bar_ptr;
            bar
        }
    }
}

impl Drop for Bar {
    fn drop(&mut self) {
        unsafe {
            foo_free(self.ptr);
        }
    }
}

extern "C" fn cb(ptr: *mut libc::c_void) {
    let bar = ptr as *mut _ as *mut Bar;
    unsafe {
        match &mut (*bar).rust_cb {
            None => panic!("Missing callback!"),
            Some(cb) => (*cb)(&mut (*(*bar).ptr).a),
        }
    }
}

fn rust_cb(a: &mut u8) {
    *a += 2;
}

fn main() {
    unsafe {
        let bar = Bar::new();
        let _ = foo_call(bar.ptr);
    }
}

I looked at related questions which seem to answer my question but solve different problems:

This uses dlsym to call a Rust callback from C.

These describe solutions for passing closures as C function pointers.

What I am trying to achieve is to have a Rust struct (Bar) which has a member variable ptr that points to a C struct (Foo), which itself has a void *internal that points back to the Rust struct Bar.

The idea is to have one trait object and wrapper function in Rust struct Bar per function pointer in C struct Foo. When a Bar object is created, we do the following:

Since the wrapper function is passed the internal pointer, we are able to get a pointer to Bar and call the respective closure (from trait obj).

I am able to point the C void* to my Rust struct and I am also able to get a pointer to it from a Rust callback (or closure), which is what the related questions address. The problem I am facing is that probably related to lifetimes because one of the values isn't living long enough to be available in the callback.


Solution

  • This is a bug (identified by @Shepmaster) in the Bar::new() function, caused due to my fundamental misunderstanding of Rust move semantics. Fixed by having Bar::new() return a Box<Bar> -

    impl Bar {
        fn new() -> Box<Bar> {
            unsafe {
                let mut bar = Box::new(Bar { ptr: foo_sys::foo_new(), rust_cb: Some(Box::new(rust_cb)) });
                (*bar.ptr).cb_mutate_a = Some(cb);
                let bar_ptr: *mut ffi::c_void = &mut *bar as *mut _ as *mut ffi::c_void;
                (*bar.ptr).internal = bar_ptr;
                bar
            }
        }
    }