c#包装到c++函数-运行一次,工作正常.运行两次,程序挂起

C# wrapper to C++ function - Run once, works okay. Run twice, program hangs

本文关键字:运行 两次 挂起 程序 工作 包装 c++ 函数 一次      更新时间:2023-10-16

所以我正在使用c#包装器到c++库,并试图添加另一个函数。我已经在c#中创建了函数声明,它正在工作。但它只能工作一次。当我第二次尝试运行它时,程序挂起了。

互操作定义和声明在https://github.com/joshglenn/interception-cs/blob/master/kchordr/Program.cs

我正在运行的代码在这里:https://github.com/joshglenn/interception-cs/blob/master/kchordr/InterceptionDemoForm.cs

第一次运行良好,但在第二次启动时挂起的函数是GetHardwareID()。

我的问题是,我如何解决这个问题?这看起来像是内存泄漏吗?

使用Marshal.GetLastWin32Error()从WinAPI调用中获取错误代码;还要记住用"Set Last Error = true"修饰调用;

下面是我调用任务栏图标弹出的一个例子:

[DllImport("shell32.dll",SetLastError=true)]
public static extern bool Shell_NotifyIcon(uint dwMessage, [In] ref NotifyIconData pnid);

用法:

//call your code like you usually call the method
bool callResult = Caller.Shell_NotifyIcon((uint)NotifyIconMessage.NIM_ADD, ref n);
//afther that call the GetLastError to get the error code
int errorCode = Marshal.GetLastWin32Error();

谷歌错误代码,看看它是什么意思