DEV Community

Discussion on: Rust Function Pointers Across FFI Boundary

Collapse
deciduously profile image
Ben Lovy Author • Edited on

To add a little more context, I was able to address the segfault by using the extern "C" fn() type:

#[no_mangle]
pub unsafe extern "C" fn run(job: *mut Job, scheduler: *mut Scheduler, work: extern "C" fn() -> ()) {
    let job = {
        assert!(!job.is_null());
        Box::from_raw(job)
    };
    let mut scheduler = {
        assert!(!scheduler.is_null());
        &mut *scheduler
    };

    job.run_extern(&mut scheduler, work)
        .unwrap_or_else(|e| eprintln!("Error: {}", e));
}
Enter fullscreen mode Exit fullscreen mode

I created a new ExternUnitToUnit struct that stores this type of function pointer and...it works, kind of. I changed the C function to this:

void job(void)
{
    exit(1);
}
Enter fullscreen mode Exit fullscreen mode

and when the job comes up to fire, the program indeed exits with a status code of 1. However, the printf statement doesn't work...hrm.

Collapse
deciduously profile image
Ben Lovy Author • Edited on

....and got there. Leaving this for posterity - STDOUT wasn't flushing. Gotta call it explicitly from C:

void job(void)
{
    //printf("Hello!  It is now %s\n", now());
    //exit(1);
    printf("Hello!");
    fflush(stdout);
}

Enter fullscreen mode Exit fullscreen mode