c# - 调用 SysFreeString() 时出现堆损坏错误

标签 c# c++ marshalling

//-------------------------- C#代码---------------- --------------

    [DllImport("MarshallStringsWin32.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    extern static void PassStringOut([MarshalAs(UnmanagedType.BStr)] out String str);

    [DllImport("MarshallStringsWin32.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    extern static void FreeString([MarshalAs(UnmanagedType.BStr)] String str);

    static void Main(string[] args)
    {
        String str;
        PassStringOut(out str);
        FreeString(str);
    }

//-------------------------- C+代码---------------- --------------

void PassStringOut(__out BSTR* str)
{
   const std::string stdStr = "The quick brown fox jumps over the lazy dog";
   _bstr_t bstrStr = stdStr.c_str();
   *str = bstrStr.copy();
}

void FreeString(BSTR str)
{
   SysFreeString(str);
}

PassStringOut() 和 FreeString() 中“str”指针的值不同,调用 SysFreeString() 时出现堆损坏错误。我应该通过引用 FreeString() 来传递“str”吗?如果是这样,我应该在 C# 和 C++ 中使用什么语法?

最佳答案

编码层将在托管内存中分配字符串的拷贝。该拷贝将由垃圾收集器释放。您不必在 C# 中将 SysFreeString 设为 String,事实上,如您所见,尝试这样做是破坏堆的好方法。

should I take it that there will be 2 copies performed on the string? The *str = bstrStr.copy(); and then by the marshalling layer?

让我更详细地描述这里发生的事情。

您的Main 方法调用非托管代码,传递类型为String 的局部变量的托管地址。编码(marshal)处理层创建自己的合适大小的存储空间来保存 BSTR 并将对该存储空间的引用传递给您的非托管代码。

非托管代码分配一个 string 对象,该对象引用与文字关联的存储,然后分配一个 BSTR 并将原始字符串的第一个拷贝放入堆中-分配的 BSTR。然后它制作该 BSTR 的第二个拷贝并使用对该存储的引用填充 out 参数。 bstrStr 对象超出范围,其析构函数释放原始 BSTR

编码层然后生成一个适当大小的托管字符串,第三次复制该字符串。然后释放传递给它的 BSTR。控制权返回到您的 C# 代码,该代码现在有一个托管字符串。

该字符串被传递给 FreeString。编码(marshal)处理层分配一个 BSTR 并第四次将字符串复制到 BSTR 中,该拷贝将传递给您的非托管代码。然后它释放一个它不拥有的 BSTR 并返回。编码(marshal)处理层释放它分配的 BSTR,破坏堆。

托管堆保持未损坏;托管字符串将在垃圾收集器选择的时间由垃圾收集器释放。

Should I pass 'str' by reference to FreeString()?

没有。相反,您应该停止编写互操作代码,直到您对编码的各个方面如何工作有了彻底深入的理解。

即使是专家也很难在托管代码和非托管代码之间编码数据。我的建议是,您应该退后一大步,在需要时获得可以教您如何安全、正确地编写互操作代码的专家的服务。

关于c# - 调用 SysFreeString() 时出现堆损坏错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18341341/

相关文章:

c++ - VS Express 2012 C++ lambda Intellisense 错误?

c# - 在 C++ 中使用 C# 嵌套结构

c# - "The subprocess making the call can not access this object because the owner is another thread"异常异步/等待 WPF C#

c# - 自动取消订阅事件

c# - SQLite 数据库锁定异常

C# 等待和处理任务

c++ - VS 2017 告诉我我正在尝试转换变量,但我没有

c++ - @selector 在C++中的实现

c# - 将指针从非托管代码返回到托管代码

C# 编码(marshal).SizeOf