小编Sha*_*onL的帖子

从c ++ DLL和c#发布SAFEARRAY

我有一个c ++函数来获取数据,我从c#调用它.该函数获取一个指向SAFEARRAY的指针并用字符串弹出它(使用SysAllocString)

一切都很好,但程序泄漏了内存.

我做了一点搜索,发现如果我将此属性添加到方法签名:

 [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)]
 out string[] strServerList
Run Code Online (Sandbox Code Playgroud)

我需要在c ++代码中释放它(它被分配),所以我创建了这个函数

 [DllImport("Native.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "DeallocateExternal")]
 internal static extern void DeallocateExternal(
 [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)]
 out string[] strServerList);
Run Code Online (Sandbox Code Playgroud)

在我的DLL中我写了这段代码

void DeallocateExternal(SAFEARRAY** psa)
{
    LONG cDims = SafeArrayGetDim(*psa);
    BSTR* pvData = (BSTR*)((*psa)->pvData); 
    for (LONG x = 0; x < cDims; x++)
    {
       SysFreeString(pvData[x]);
    }
    SafeArrayDestroy(*psa); 
}
Run Code Online (Sandbox Code Playgroud)

但我有一个例外:

Tester.exe中发生了未处理的"System.AccessViolationException"类型异常

附加信息:尝试读取或写入受保护的内存.这通常表明其他内存已损坏.

怎么了?

c# c++ memory interop safearray

9
推荐指数
1
解决办法
2918
查看次数

标签 统计

c# ×1

c++ ×1

interop ×1

memory ×1

safearray ×1