How to pass pass a closure or Fn as an extern C callback without user argument

⚓ Rust    📅 2026-01-11    👤 surdeus    👁️ 1      

surdeus

Hello,

I've made some research about how to pass a closure or a Fn to a C function as a callback.

I've mostly learnt that it's unfortunately not that simple. But it can be done only if the callbacks accepts a user defined data, from which one can pass the Fn as an argument / pointer to the callback.

If the callback doesn't accept user defined data, only static functions will work.

In my case I am lucky to have the callback accepting a user defined data that can be passed to the function.

But, out of curiosity, how would one write something like that:

// Callback doesn't allow any user defined data
pub type Callback = unsafe extern "c" fn(<some arguments>);

unsafe extern "c" set_callback(callback: *mut Callback);

// especially this part
fn set_my_callback(callback: ???) {
    unsafe { set_callback(callback) }; /// ??
}

Hoping I was clear enough.

Thank you very much in advance for any help

5 posts - 3 participants

Read full topic

🏷️ Rust_feed