gpt4 book ai didi

c# - 使用 VS 2010 调试导入的 dll

转载 作者:可可西里 更新时间:2023-11-01 10:34:56 24 4
gpt4 key购买 nike

我在尝试从 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. 在 Visual Studio 中启用非托管代码调试。注意:VS 2010 Express 不支持混合托管/非托管调试。 ( Instructions )
  2. 使用WinDbg .这将是我个人最喜欢的调试混合应用程序的选项。这是一个非常强大的工具。诚然,学习曲线有点陡峭,但值得付出努力。
  3. 使用 OllyDbg 等外部/第三方调试器。 (根据 MrDywar 的建议)

P/Invoke 问题:

  1. 作为IInspectable指出 HWND 应该使用 IntPtr 传递给非托管代码。
  2. > Windows API data types定义明确。 DWORD 始终为 32 位。此外,LONG(全部大写)与 long(小写)不同。

C++ 问题:

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

关于c# - 使用 VS 2010 调试导入的 dll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32530358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com