9
我有一個C++函數獲取數據和我把它叫做從C#。這個函數會得到一個指針SAFEARRAY與字符串(使用SysAllocString)poplate它釋放SAFEARRAY從C++ DLL和C#
一切正常,但程序正在泄漏內存。
我做了一些搜索和發現,如果我這個屬性添加到方法簽名:
[MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)]
out string[] strServerList
我需要釋放它在C++代碼(它被分配的),所以我創造了這個功能
[DllImport("Native.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "DeallocateExternal")]
internal static extern void DeallocateExternal(
[MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)]
out string[] strServerList);
而且在我的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);
}
但我得到了一個例外:
型「System.AccessViolationException」未處理的異常發生在Tester.exe
其他信息:試圖讀取或寫入保護內存。這通常表明其他內存已損壞。
出了什麼問題?
您需要使用SafeArrayGetUBound而不是SafeArrayGetDim請參閱http://msdn.microsoft.com/en-us/library/aed339d5-d962-4adc-ac01-6c15a54c51ca%28VS.85%29 – Yahia