I want to point pthread_create to a C function I later link to. That C function will use pthread_cleanup_push and pthread_cleanup_pop which are C macros and thus cannot be ported to Rust.
This is my code:
extern crate libc;
use std::ptr::null_mut;
use libc::c_void;
extern "C" {
fn thr_fn1(arg:*mut c_void) -> *mut c_void;
}
fn main() {
let mut tid1 = std::mem::zeroed();
libc::pthread_create(&mut tid1, null_mut(), thr_fn1, null_mut());
}
I expected that since I'm calling libc's FFI anyway, I can just point to an external C function, but I get an error:
error[E0308]: mismatched types
--> src/bin/11-threads/f05-thread-cleanup.rs:25:49
|
25 | libc::pthread_create(&mut tid1, null_mut(), thr_fn1, null_mut());
| ^^^^^^^ expected normal fn, found unsafe fn
|
= note: expected type `extern "C" fn(*mut libc::c_void) -> *mut libc::c_void`
found type `unsafe extern "C" fn(*mut libc::c_void) -> *mut libc::c_void {thr_fn1}`
I could write a wrapper which calls the C function in an unsafe{} block, but is there any way to avoid that?
pthread_createfrom your C code and skip the whole song and dance. - Shepmasterextern "C" fn wrapped_fn1(arg: *mut c_void) -> *mut c_void { unsafe { thr_fn1(arg) } }and passwrapped_fn1topthread_create. Also, you will need anunsafeblock inmainto invokelibc::pthread_createandstd::mem::zeroed. - user4815162342