C语言中的回调方法 [英] Call back method in C
本文介绍了C语言中的回调方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从C dll文件调用一个C#函数,我的需要是在我的C dll文件知道的特定时间段内在我的C#应用程序中调用一个函数.
为此,我创建了一个示例代码对其进行测试,但是它对我不起作用.
任何人对此都有任何想法,请纠正我
我的示例代码在下面给出
C dll代码
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
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#控制台应用程序
C# console application
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 ...");
}
}
推荐答案
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)
这篇关于C语言中的回调方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文