【问题标题】:C# wrapper to C++ function - Run once, works okay. Run twice, program hangsC# 包装器到 C++ 函数 - 运行一次,工作正常。运行两次,程序挂起
【发布时间】:2014-03-19 14:55:09
【问题描述】:

所以我正在使用 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()。

我的问题是,我该如何解决这个问题?这似乎是内存泄漏?

【问题讨论】:

    标签: c# c++ interop language-interoperability


    【解决方案1】:

    要从 WinAPI 调用中获取错误代码,请使用 Marshal.GetLastWin32Error(); 还记得用“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();
    

    google 一下错误代码,看看是什么意思

    【讨论】:

    • 谢谢。那会派上用场的。事实证明,我的错误是由于底层 API 使用不当引起的。我的函数声明是正确的。再次感谢!
    • 原来我的函数声明没问题。我错误地使用了底层 API。我将您的答案标记为答案,因为这应该可以帮助其他人解决类似问题。
    猜你喜欢
    • 1970-01-01
    • 2020-08-03
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多