Sha*_*onL 9 c# c++ memory interop 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"类型异常
附加信息:尝试读取或写入受保护的内存.这通常表明其他内存已损坏.
怎么了?
我想你应该试试:
...
SafeArrayDestroy(*psa);
*psa = NULL
...
Run Code Online (Sandbox Code Playgroud)
这样做的原因是你声明strServerList
为out
,所以.Net编组器会尝试将指向无效(释放)内存的指针转换为字符串数组,这可能会引发异常.
归档时间: |
|
查看次数: |
2918 次 |
最近记录: |