Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot Generate Delegate for Public Type RustCallback = extern "C" fn() #101

Open
Yongle-Fu opened this issue Feb 28, 2025 · 0 comments
Open

Comments

@Yongle-Fu
Copy link

Yongle-Fu commented Feb 28, 2025

I’m encountering an issue where I cannot properly generate a delegate in C# for a Rust function pointer type defined as pub type BatteryLevelCallback = extern "C" fn(id: *const c_char, battery_level: u8). The Rust code exposes this type and a corresponding function, but the C# interop seems to fail when defining the delegate.

#[no_mangle]
pub extern "C" fn callback_test(cb: extern "C" fn(a: i32) -> i32) -> i32 {
    cb(100)
}

pub type BatteryLevelCallback = extern "C" fn(id: *const c_char, battery_level: u8);

#[no_mangle]
pub extern "C" fn set_battery_level_callback(callback: BatteryLevelCallback) {
    // Placeholder for callback usage
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int callback_test_cb_delegate(int a);

[DllImport(__DllName, EntryPoint = "callback_test", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
internal static extern int callback_test(callback_test_cb_delegate cb);

// Attempted delegate for BatteryLevelCallback - this is where the issue arises
[DllImport(__DllName, EntryPoint = "set_battery_level_callback", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
internal static extern void set_battery_level_callback(set_battery_level_callback_callback_delegate callback);

Problem
The callback_test function works as expected with its delegate callback_test_cb_delegate.
However, defining a delegate for set_battery_level_callback (e.g., set_battery_level_callback_callback_delegate) fails. The C# compiler or runtime does not recognize or properly bind to the BatteryLevelCallback type

Expected Behavior
I expect to define a delegate in C# that matches the BatteryLevelCallback type, allowing me to pass a callback function from C# to Rust via set_battery_level_callback.

Additional Notes
The callback_test example with a simple i32 parameter and return type works fine, suggesting the issue is specific to the BatteryLevelCallback signature.
Is there a correct way to define the delegate for extern "C" fn(id: *const c_char, battery_level: u8) in C#?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant