从C#调用VC ++ dll中的回调函数

时间:2012-02-08 08:30:24

标签: c# callback

我需要从C#应用程序中调用VC ++ dll中的回调函数。以下是VC ++中的回调函数。

INT_PTR CALLBACK My_Proc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    . . . . .   
}

我已经导入了dll,但我不知道如何从C#调用该函数。有什么想法吗?

public class testClass
{
    internal static class UnsafeNativeMethods
    {
        const string _dllLocation = "test.dll";

        [DllImport(_dllLocation, CallingConvention = CallingConvention.Cdecl)]
        public static extern int My_Proc(int value1, int value2, Int64 value3, int value4);// am getting stuck here

    }
}

2 个答案:

答案 0 :(得分:2)

正确的声明是:

    [DllImport("test.dll", CallingConvention = CallingConvention.StdCall)]
    public static extern IntPtr My_Proc(IntPtr hDlg, int message, IntPtr wparam, IntPtr lparam);

这是本机对话框的对话框过程的声明。 Windows应该叫它,而不是你。当对话框有新的Windows消息时,它会这样做。它很少从DLL导出,这也可以解释有问题。获得正确的窗口句柄(hDlg)也不容易。但你没有很好地记录你的问题所以我只能猜测。

答案 1 :(得分:0)

在VC ++中你应该使用dll句柄:

hInst = ::GetModuleHandle("test.dll");
DialogBox(hInst, MAKEINTRESOURCE(IDD_DIALOG1), NULL, My_Proc);