Passing generic type parameter to external C function

Recently, I am trying to build a function that accepts generic type parameters, sent to FFI and deref in external C function. It's said that deref() function can deref the raw pointer passed from Rust and print the value of any type.

extern "C" {
    fn deref(ctx: *const c_void, name: *const c_void);
}

pub fn new_generic<T>(
    p1: T,
    p2: Option<T>
) -> u32 {
    unsafe {
        let p2_ptr = p2.map_or(ptr::null_mut(), |s| s.as_ptr() as *mut _);
        deref(p2_ptr, p1.as_ptr() as *mut _);
    }
    // ...
}

However, it always shows the error:

as_ptr() method not found in `T`

It makes sense. The compiler can't identify the type so not sure whether T has the method as_ptr(). Is there any suggestion to fix such issue? (maybe I should give a trait bound?)

If you just need a pointer to p1 that's valid for the duration of deref and no longer, you can just take a reference to the variable and cast it to a raw pointer. If you need a more stable memory address you'll need to define a trait for types that have a stable address that defines a method like that.

Yes. At the end, I use &mut name as *mut _ as *mut c_void to pass the generics.

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.