Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marshaling a method pointer with pointer argument in C#

Tags:

c#

interop

cil

I need to marshal a method pointer with a pointer argument, like so in C:

void (*callback)(int *x);

How would I write that as struct field in C#?

Note: I don't mind having the CLR dereference the pointer for me.

like image 227
Charles Avatar asked Jul 29 '26 07:07

Charles


1 Answers

If your method expects a callback accepting a pointer to any structure, you can pass a managed callback when specifying your P/Invoke DllImports like this:

private delegate void MyCallback(IntPtr par);

[DllImport("MyLibrary.dll")]
public static extern void SomeFunction(MyCallback callback);

You can then Marshal the IntPtr to an appropriate structure inside your actual callback method.

[Edit]

To pass an int parameter by reference, following delegate signature should work best:

private delegate void MyCallback(ref int par);
like image 61
Groo Avatar answered Jul 31 '26 20:07

Groo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!