[英]Debug an imported dll with VS 2010
我在嘗試從 C# 代碼調用 WinAPI 函數時遇到問題。 我有很多導入,其中許多工作正常,但其中一些沒有並導致意外中斷主程序,沒有任何消息,異常類型,什么都沒有,只是掉下所有窗口並退出。
我在代碼中有兩種方法:通過我開發的庫,那里有更多的 winapi 調用,我懶得編寫特定的結構、指針等,直接從 user32.dll 導入,如下所示:
[DllImport(@"tradeInterop.dll")]
public static extern void ChooseInstrumentByMouse(UInt32 hwnd, int baseX, int baseY, int idx, int _isDown);
[DllImport(@"tradeInterop.dll")]
public static extern void PutNumber(int num);
[DllImport(@"tradeInterop.dll")]
public static extern void PutRefresh();
[DllImport(@"user32.dll")]
public static extern UInt32 FindWindow(string sClass, string sWindow);
[DllImport(@"user32.dll")]
public static extern int GetWindowRect(uint hwnd, out RECT lpRect);
[DllImport(@"user32.dll")]
public static extern int SetWindowPos(uint hwnd, uint nouse, int x, int y, int cx, int cy, uint flags);
[DllImport(@"user32.dll")]
public static extern int LockSetForegroundWindow(uint uLockCode);
[DllImport(@"user32.dll")]
public static extern int SetForegroundWindow(uint hwnd);
[DllImport(@"user32.dll")]
public static extern int ShowWindow(uint hwnd, int cmdShow);
[DllImport(@"tradeInterop.dll")]
public static extern ulong PixelColor(uint hwnd, int winX, int winY); //tried (signed) long and both ints as return type, same result (WINAPI says DWORD as unsigned long, what about 64-bit assembly where compiled both lib and program?
public struct RECT
{
public int Left;
public int Top; ...
正如我所說,其中許多調用都可以完美運行,但最后兩個調用存在問題:ShowWindow() 和 PixelColor(),代碼如下:
extern "C" __declspec(dllexport) COLORREF __stdcall PixelColor(unsigned hwnd, int winX, int winY)
{
LPPOINT point;
point->x = winX;
point->y = winY;
ClientToScreen((HWND) hwnd, point);
HDC dc = GetDC(NULL);
COLORREF colorPx = GetPixel(dc, point->x, point->y);
ReleaseDC(NULL, dc);
return colorPx;
}
因此,當我嘗試調用直接導入的 ShowWindow() 函數或調用 api 函數的庫時,我遇到了程序崩潰
有什么方法可以調試外部庫及其結果嗎?
我做錯了什么?
非常感謝
您有多種調試問題的選項。
WinDbg
。 這將是我個人最喜歡的調試混合應用程序的選項。 這是一個非常強大的工具。 誠然,學習曲線有點陡峭,但值得付出努力。P/Invoke 問題:
HWND
應該使用IntPtr
傳遞給非托管代碼。DWORD
始終為 32 位。 此外, LONG
(全部大寫)與long
(小寫)不同。C++ 問題:
LPPOINT
從未初始化,因此當您調用ClientToScreen()
您將未初始化的堆棧垃圾作為指針訪問並分配值。 要修復它,您可以:
LocalAlloc
, GlobalAlloc
, malloc
, calloc
。POINT point;
,使用point.x
& point.y
分配值,並在函數調用中使用它作為&point
。HWND
。 API 類型,即使它們最終是 typedef,也帶有額外的含義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.