Click here to Skip to main content
15,909,896 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to call one C# function from C dll file, My need is to invoke one function in my c# application in a particular time period that my C dll file knows

for that I create one sample code for testing it, But its not working to me.

any one have any idea about this please correct me
My sample code is given below

C dll code
C++
extern "C"
{
	
	void (*foo1)(int)= NULL;
  __declspec(dllexport) void DisplayHelloFromDLL()
  {
	
	   //foo = &my_int_func;
	  foo1(2);
    printf ("Hello from DLL !\n");
	

  }

   __declspec(dllexport) void InitializeFun(void (*foo)(int)) 
  {
	  foo1=foo;
	}

 

}


C# console application

C#
public class NativeMethods
   {
       private const string KERNEL32_DLL = "Kernel32.dll";
       [DllImport(KERNEL32_DLL)]
       static internal extern IntPtr LoadLibrary(string szFileName);
       [DllImport(KERNEL32_DLL)]
       static internal extern IntPtr GetProcAddress(IntPtr hLibrary, string szProcName);
       [DllImport(KERNEL32_DLL)]
       static internal extern int FreeLibrary(IntPtr hLibrary);
   }


   class Program
   {
       [DllImport("TestLib.dll")]
       public static extern void DisplayHelloFromDLL();

       [DllImport("TestLib.dll")]
       public static extern void InitializeFun(VoidDelegate MyFunc);

       public delegate void VoidDelegate();


       static void Main(string[] args)
       {
           Console.WriteLine("This is C# program");

           IntPtr hUser32 = NativeMethods.LoadLibrary("TestLib.dll");
           IntPtr pMethod = NativeMethods.GetProcAddress(hUser32, "InitializeFun");



           VoidDelegate method2 = (VoidDelegate)Marshal.GetDelegateForFunctionPointer(pMethod, typeof(VoidDelegate));
           InitializeFun(method2);

           DisplayHelloFromDLL();
           string str = Console.ReadLine();


       }

       public static void MyFunc()
       {
           Console.WriteLine("I was called by c dll ...");
       }
   }
Posted
Comments
BobJanova 21-Feb-12 6:18am    
Define 'isn't working'.

1 solution

VoidDelegate method2 = (VoidDelegate)Marshal.GetDelegateForFunctionPointer(pMethod, typeof(VoidDelegate));

Why are you doing this? Surely you just want
VoidDelegate method2 = MyFunc;


Actually you might well just be able to do
InitializeFun(MyFunc)
 
Share this answer
 
Comments
Arun Kumar K S 21-Feb-12 23:32pm    
many thanks BobJanova its worked to me, One more doubt when I passed integer argument it called the function and c lose the application immediately
BobJanova 22-Feb-12 14:15pm    
You need to declare the delegate to take an int.
Arun Kumar K S 21-Feb-12 23:33pm    
my 5 vote to your answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900