我希望将pthread_create
指向我稍后链接到的C函数,该C函数将使用pthread_cleanup_push
和pthread_cleanup_pop
,这些都是C宏,因此无法移植到Rust。
以下是我的代码:
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());
}
我原本以为既然我已经在调用libc的FFI,那么我可以直接指向一个外部的C函数,但是我却收到了一个错误:
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}`
我可以编写一个包装器,在unsafe{}
块中调用C函数,但有没有避免这种情况的方法?
pthread_create
,跳过整个繁琐的过程。 - Shepmasterextern "C" fn wrapped_fn1(arg: *mut c_void) -> *mut c_void { unsafe { thr_fn1(arg) } }
并将wrapped_fn1
传递给pthread_create
。此外,在main
中需要一个unsafe
块来调用libc::pthread_create
和std::mem::zeroed
。 - user4815162342