Call and check function pointer from C dll

Hi all.

I'm dealing with an external .so dll library on Linux. This is and extract of my code:

use libc::{c_int, c_ulong};

type ExtFunc = extern "C" fn(arg1: c_ulong);

#[derive(Clone, Debug)]
struct ComesFromDLL {
    field1: c_ulong,
    field2: c_int,
    func_pointer: *const ExtFunc

fn main() {

    /* ... dll loading using libloading crate ... */
    let descriptor_struct: ComesFromDLL = /* ... calling a function dll to get a pointer to ComesFromDLL struct */


the struct ComesFromDLL is defined just like the dll's .h file. I can read the field1 and field2 fields and they are correct. So far, so good.

My problem is that I need to check if func_pointer is null in order to know if I can call that function or not, as per dll specifications; if I define the field as (A):

func_pointer: *const ExtFunc

i can check if it is null with descriptor_struct.func_pointer.is_null() , and it works.
If I define the field as (B):

func_pointer: ExtFunc

I can call the function using (descriptor_struct.func_pointer)(10, 20); and it works.
But I can't do both. If I define the field as (A) I get a call expression requires function error when I try to call the function and in case (B) the .is_null() method isn't available.

I suspect my approach here isn't right.

What should I do?


"Nullable function pointer" is Option<fn(...) -> ...> (or, in your case, Option<ExtFunc>), with null corresponding to None.

1 Like

Wow... I didn't know Option can be used even for that. Thanks a lot!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.