且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查从C传递的函数指针是否为非NULL

更新时间:2023-11-28 10:32:58

您可以使用Option<...>表示可为空的函数指针.对于类型为fn(...)的值具有NULL值是不正确的,因此在这种情况下需要使用Option包装器.

You can use Option<...> to represent nullable function pointers. It is incorrect to have a NULL value for a value of type fn(...) so the Option wrapper is required for cases like this.

例如,

#[no_mangle]
pub extern "C" fn call_c_function(value: i32, fun: Option<fn(i32) -> i32>) -> i32 {
    if let Some(f) = fun {
        f(value)
    }
}

但是,还有一个要点:fun是C函数,而类型fn(...)是Rust函数.它们不直接兼容(例如,它们的调用约定不同).与C函数指针进行交互时,需要使用extern "C" fn(...)(也称为extern fn(...))类型:

However, there's one extra point: fun is a C function, but the type fn(...) is a Rust function. They're not directly compatible (e.g. their calling conventions differ). One needs to use the extern "C" fn(...) (a.k.a. extern fn(...)) type when interacting with C function pointers:

#[no_mangle]
pub extern "C" fn call_c_function(value: i32, fun: Option<extern "C" fn(i32) -> i32>) -> i32 {
    if let Some(f) = fun {
        f(value)
    }
}