Explicit P/Invoke: Callbacks from native code

In the previous article I discussed how explicit p/invoke is used to call native code from the managed code. Here I ‘ll discuss what if native code needs to call managed code?
We can utilize Delegates for this purpose i.e. we can pass delegate as the parameter and then the native code can cast this as function pointer and store it for later use. This function pointer can be used to call managed code.
The following example demonstrates how to configure an unmanaged API to trigger a managed delegate.

[DllImport(@"path\Example.dll", ExactSpelling = true, CharSet = CharSet.Ansi)]
public static extern int CallBack(CallBackMethodDelegate delCallback, int n);

public delegate int CallBackMethodDelegate(int n);

public static int CallBack(int n)
return n / 2;

The following code shows how to register this delegate to native code and make it call back.

CallBackMethodDelegate delCallback = new CallBackMethodDelegate(CallBack);
int iResult = CallBack(delCallback,n);

The following is the native code for this example.

int CallBack(int (_stdcall *pFnCallBack)(int), int iParam)
int iProcessedInManagedValue = pFnCallBack(iParam);
return iProcessedInManagedValue;

The function pointer remains valid as long as delegate is inside managed code. So if your native application needs to store it for later use make sure corrosponding delegate exists for the same duration and does not get garbage collected.

Explore posts in the same categories: Programming


You can comment below, or link to this permanent URL from your own site.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: