How can I pass an unsafe function when a safe function is expected without wrapping the unsafe function?

I want to point pthread_createto a C function that I refer to later. This C function will use pthread_cleanup_pushand pthread_cleanup_pop, which are C macros and therefore 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 still call libc FFI, 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 that calls the C function in the block unsafe{}, but is there a way to avoid this?

+4
source share
1 answer

Function definition libcincorrect: C header /usr/include/pthread.h:

extern int pthread_create (pthread_t *__restrict __newthread,
                           const pthread_attr_t *__restrict __attr,
                           void *(*__start_routine) (void *),
                           void *__restrict __arg) __THROWNL __nonnull ((1, 3));

bindgen :

pub fn pthread_create(arg1: *mut pthread_t,
                      arg2: *const pthread_attr_t,
                      arg3: Option<unsafe extern "C" fn(arg1: *mut c_void) -> *mut c_void>,
                      arg4: *mut c_void) -> c_int;

macOS, Linux. , Option - ; - , ?

PR libc, ( Option)

+1

Source: https://habr.com/ru/post/1669992/


All Articles