Charles
Charles

Reputation: 6307

Marshaling a method pointer with pointer argument in C#

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.

Upvotes: 3

Views: 1195

Answers (1)

vgru
vgru

Reputation: 51214

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);

Upvotes: 4

Related Questions