[英]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.