使用VS 2010调试导入的dll

时间:2015-09-11 18:55:35

标签: c# c++ c windows winapi

我尝试从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函数的库时,我遇到程序崩溃

有没有办法调试外部库及其结果?

我做错了什么?

非常感谢

1 个答案:

答案 0 :(得分:1)

您有几种调试问题的选项。

  1. 在Visual Studio中启用非托管代码调试。注意:VS 2010 Express不支持混合托管/非托管调试。 (Instructions
  2. 使用WinDbg。这将是我个人最喜欢的调试混合应用程序的选项。这是一个非常强大的工具。不可否认,学习曲线有点陡峭,但值得付出努力。
  3. 使用像OllyDbg这样的外部/第三方调试程序。 (根据MrDywar
  4. 的建议

    P / Invoke问题:

    1. 由于IInspectable指出HWND应使用IntPtr传递给非托管代码。
    2. Windows API data types定义明确。 DWORD总是32位。此外,LONG(全部上限)与long(小写)不同。
    3. C ++问题:

      1. IInspectable所述,LPPOINT永远不会被初始化,因此当您调用ClientToScreen()时,您将访问未初始化的堆栈垃圾作为指针,并分配值。要修复它你可以:
        1. 分配内存(此处最喜欢的方案,LocalAllocGlobalAllocmalloccalloc
        2. 制作声明POINT point;,使用point.x&分配值。 point.y,并在函数调用中将其用作&point
      2. 制作第一个参数的类型HWND。 API类型,即使它们最终是typedef,也带有额外的含义。