Click here to Skip to main content
15,868,141 members
Articles / Programming Languages / C#
Article

Calling Managed .NET Function from Unmanaged Windows Custom DLL.

Rate me:
Please Sign up or sign in to vote.
2.92/5 (11 votes)
25 Apr 20043 min read 120.2K   26   28
It will help you to call a managed function from unmanaged DLL function.

Introduction

Is it possible?

Yes, it is absolutely possible, but you have to remember one thing. You can’t call a .NET function from a Win32 Process. It is ever never possible until you externally load the CLR. So, in this article, we are going to see how to call a .NET function from a Windows Custom DLL (for example, a DLL written in VC++), within a .NET process.

Is it needful?

Yes, it will be needful. Developers who are working in Win32 API from .NET, some time requires notification from unmanaged code to a managed function in .NET environment (for example, to notify completion of an asynchronous call). At that time, they can use this methodology to complete their task.

Is the Example given useful?

No, we take this code example for demonstration purpose only. In this example, we are going to call an unmanaged code from managed code, and the unmanaged code itself again calls another managed code (you can use this technique to notify the .NET environment about an asynchronous event from unmanaged code).

Basic Idea

Usually, we can call a function through two methods. The first one is using function name, and the next one is through the function pointer. Here, we are going to call a function from another (unmanaged) environment, so we can’t use the function name directly, so we are going to use function pointer. The first step is, we have to give the function pointer to unmanaged code, and then the unmanaged code will use this function pointer to call the managed code.

The core thing is described in the following figure:

Image 1

For checking that, we will create one custom DLL in VC++, and implement two functions. One is SetCallBackPointer, which receives a function pointer from managed code and stores it in a global variable pFunction. Another function InvokeCallBack is to call the managed code using function pointer pFunction. Here is the code residing in the DLL source file.

// MyCustomDll.cpp
//Global Variable for store the function pointer.
 
typedef VOID (*CALLBACK_FUNCTION )();
CALLBACK_FUNCTION pFunction;
 
void SetCallBackPointer(LPVOID FnAddress);
void InvokeCallBack();
 
 
//This function receive the address of the CallBack function as
//parameter and store it in a global variable to enable other function in 
// the DLL to call the CallBack Function.
 
void SetCallBackPointer(LPVOID FnAddress)
{
      pFunction = (CALLBACK_FUNCTION)FnAddress;
// For demonstration purpose only. In real World we may call 
// this function in response to a asynchronous message.
      InvokeCallBack();
}
 
// this function will Invoke the callback function 
// through the function pointer.
void InvokeCallBack()
{
     (pFunction)(); // simply calls the Callback function through pointer.
}

Then we have to export the SetCallBackPointer to make it callable from out of the DLL.

// MyCustomDll.def
//
LIBRARY MYCUSTOMDLL
EXPORTS
SetCallBackPointer

OK, now we can build our DLL and create MyCustomDll.dll. Next, we are going to write the C# code for the callback function:

C#
//       Managed.cs 
//
 
//  Our Callback function which will be called by unmanaged code(Form windows dll).
public static void CallbackFunction()
{
      MessageBox.Show( "CallBack Function Called by Windows DLL");
}

We can’t directly give the function name as the function pointer as we do it in C, C++ or VC++. Fortunately, we can do that using delegates. (I hope that you are all familiar, with one of .NET’s wonderful future: delegates. If you are not familiar with delegates, please refer MSDN.)

Let’s declare a delegate and instantiate it as follows.

C#
// Declaring Delegate for Callback Function
// note that the Delegate prototype and Callback function 
// prototype are same.
 
delegate void CallBackDelegate();
public static  CallBackDelegate myDelegate;

Next, we have to associate our callback function with the delegate:

C#
// Associating callback function with delegate
myDelegate =new MyDelegate(CallbackFunction);

OK, now our function pointer is ready. Next step is, we have to send it to the DLL. To render the callback function (that is delegate) to DLL, we have to call SetCallBackPointer function in the custom DLL. For that, we have to declare a function prototype of SetCallBackPointer with DllImport attribute. Here is the declaration:

C#
// this function prototype should match our Custom dll’s 
// ‘SetCallBackPointer’ functioin prototype.
//
[DllImport("MyCustomDll.dll",CallingConvention=CallingConvention.StdCall)]
private static extern void SetCallBackPointer(CallBackDelegate delegate);

Everything is ready now; remaining is, we have to call SetCallBackPointer function. The following call will invoke the SetCallBackPointer function in the MyCustomDll with CallBackFunction function pointer (delegate) as the argument:

C#
SetCallBackPointer(myDelegate);

Yes we got it, CallBackFunction is called from our custom DLL.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Technical Lead GE Healthcare
India India
Hey, I am mohamed hasan. Working as a software engineer in a India based Software Company.
Willing to learn new concepts and technologies.

Contact him at: hasansheik@gmail.com
hasansheik@yahoo.co.in

Comments and Discussions

 
GeneralMy vote of 5 Pin
Sivaraman Dhamodharan3-Nov-10 0:51
Sivaraman Dhamodharan3-Nov-10 0:51 
My vote of 5 Hasan.
Questionthird party dll Pin
AGraca20-Nov-07 5:22
AGraca20-Nov-07 5:22 
GeneralProblem when passing 2 parameters Pin
Chathruwan18-Sep-07 1:09
Chathruwan18-Sep-07 1:09 
Generalnice article Pin
Girish Nurani Sankaranarayanan20-May-07 20:35
Girish Nurani Sankaranarayanan20-May-07 20:35 
GeneralAPI problem Pin
t4ure4n7-Aug-06 4:28
t4ure4n7-Aug-06 4:28 
GeneralCatching ActiveX callback in C# Pin
anderslundsgard8-May-06 2:15
anderslundsgard8-May-06 2:15 
GeneralThis worked great with some changes... Pin
kayakdog247-Dec-05 8:29
kayakdog247-Dec-05 8:29 
AnswerRe: This worked great with some changes... Pin
kayakdog249-Dec-05 4:28
kayakdog249-Dec-05 4:28 
GeneralDelphi 7 Pin
Cstruter6-Nov-05 20:13
Cstruter6-Nov-05 20:13 
QuestionThanks for this article! But how can i call a delegate with params? Pin
CityWolf30-Oct-05 0:21
CityWolf30-Oct-05 0:21 
AnswerRe: Thanks for this article! But how can i call a delegate with params? Pin
danielei30-Nov-05 4:54
danielei30-Nov-05 4:54 
AnswerFOUND A SOLUTION TO CALLBACK WITH PARAMS!!! Pin
kayakdog249-Dec-05 9:11
kayakdog249-Dec-05 9:11 
GeneralRe: FOUND A SOLUTION TO CALLBACK WITH PARAMS!!! Pin
aitzi13-Dec-05 23:44
aitzi13-Dec-05 23:44 
GeneralDoes not work for .net/c++ Pin
Anonymous8-Apr-05 7:44
Anonymous8-Apr-05 7:44 
QuestionWill this work for what I am trying to do? Pin
feldergarbfeldergarb10-Dec-04 9:56
feldergarbfeldergarb10-Dec-04 9:56 
GeneralDirect calling of managed code Pin
Wraith227-Apr-04 1:05
Wraith227-Apr-04 1:05 
GeneralRe: Direct calling of managed code Pin
hasansheik27-Apr-04 2:01
hasansheik27-Apr-04 2:01 
GeneralRe: Direct calling of managed code Pin
Wraith227-Apr-04 2:48
Wraith227-Apr-04 2:48 
GeneralRe: Direct calling of managed code Pin
skboey12-Jul-04 23:50
skboey12-Jul-04 23:50 
GeneralRe: Direct calling of managed code Pin
Wraith213-Jul-04 0:21
Wraith213-Jul-04 0:21 
GeneralRe: Direct calling of managed code Pin
skboey13-Jul-04 1:51
skboey13-Jul-04 1:51 
GeneralRe: Direct calling of managed code Pin
Wraith213-Jul-04 3:36
Wraith213-Jul-04 3:36 
GeneralRe: Direct calling of managed code Pin
skboey14-Jul-04 0:12
skboey14-Jul-04 0:12 
GeneralI doubt this will work correctly Pin
leppie26-Apr-04 7:10
leppie26-Apr-04 7:10 
GeneralRe: I doubt this will work correctly Pin
Heath Stewart26-Apr-04 8:15
protectorHeath Stewart26-Apr-04 8:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.