[英]Exception when closing a Win32 dialog box in dll (from WPF application)
我有一个从DLL调用C ++函数的C#应用程序。 C ++函数仅显示一个对话框和一个退出按钮。
DLL中的C ++函数如下所示:
//the exported function for clients to call in DLL
HINSTANCE hInstance;
__declspec(dllexport) int __cdecl StartDialog(string inString)
{
hInstance = LoadLibrary(TEXT("My.dll"));
DialogBox(hInstance, MAKEINTRESOURCE(ID_DLL_Dialog), NULL, DialogProc);
return 1;
}
BOOL CALLBACK DialogProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDD_BUTTON_EXIT:
DestroyWindow(hwnd);
return TRUE;
}
}
return FALSE;
}
如果我在一个简单的C ++程序中调用StartDialog
函数,它将起作用。 我可以显示该对话框,并且在单击对话框中的退出时可以正确关闭它。
typedef int(__cdecl *StartDialogFunc)(string);
StartDialogFunc StartDialog = nullptr;
HINSTANCE hDll = LoadLibrary(TEXT("My.dll"));
StartDialog = (StartDialogFunc)GetProcAddress(hDll, "StartDialog");
int i = StartDialog("hello"); //this is working
cout << i;
如果我在C#应用程序中调用它,则单击退出按钮后,对话框将关闭,并给我一个例外。 C#代码如下所示:
[DllImport("My.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int StartDialog(string s);
int i = StartDialog("hello"); //this causes a exception
错误消息是这样的:
调试断言失败!
程序:(某些路径...)My.dll
文件:d:\\ program files(x86)\\ Microsoft Visual Studio 14.0 \\ vc \\ include \\ xmemory0
线:100
表达式:“((_ Ptr_user&(_BIG_ALLOCATION_ALIGNMENT-1))== 0” && 0
有关程序如何导致断言失败的信息,请参见有关断言的Visual C ++文档。
我怎么知道DLL中到底有什么问题?
尝试将C ++函数签名更改为WCHAR*
,因为C ++的std::string
与C#不兼容。 另外,要获取当前DLL的句柄,请使用GetModuleHandle(NULL),而不是LoadLibrary。
HINSTANCE hInstance;
__declspec(dllexport) int __cdecl StartDialog(const WCHAR* inString)
{
hInstance = GetModuleHandle(NULL);
DialogBox(hInstance, MAKEINTRESOURCE(ID_DLL_Dialog), NULL, DialogProc);
return 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.