用vs2010调试导入的dll
本文关键字:dll 导入 调试 vs2010 | 更新日期: 2023-09-27 18:12:27
我有一个问题,而我试图从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函数的库时,我得到了程序崩溃
是否有任何方法如何调试外部库及其结果?
我做错了什么?
Thanks to lot
您有几个选项来调试问题。
- 在Visual Studio中启用非托管代码调试。注意:VS 2010 Express不支持混合托管/非托管调试。(指令)
- 使用
WinDbg
。这是我个人在调试混合应用程序时最喜欢的选项。这是一个非常强大的工具。不可否认,学习曲线有点陡峭,但它非常值得努力。使用外部/第三方调试器,如OllyDbg。(根据MrDywar的建议)
p/Invoke问题:
- 正如IInspectable指出的,
HWND
应该通过IntPtr
传递给非托管代码。 - Windows API数据类型定义良好。
DWORD
总是32位。另外,LONG
(全大写)和long
(小写)也不一样。
c++问题:
- 正如IInspectable所提到的,
- 分配内存(您最喜欢的方案,
LocalAlloc
,GlobalAlloc
,malloc
,calloc
) - 声明
POINT point;
,使用point.x
&point.y
,并在函数调用中作为&point
使用。 - 设置第一个参数的类型为
HWND
。API类型,即使它们最终是类型定义,也带有额外的含义。
LPPOINT
永远不会初始化,所以当你调用ClientToScreen()
时,你将访问未初始化的堆栈垃圾作为指针,并赋值。要修复它,您可以: