我試圖從C++(COM)通過結構的陣列,以C#傳遞結構的陣列從C++(COM),以C#
//C++ definition
//MyStruct being a COM Visible Structure
HRESULT GetArrofStruct([in,out] LONG* count, [out,size_is(,*pnCnt)] MyStruct** ppArr);
//C# definition
void GetArrofStruct(ref int Count,out IntPtr outPtr);
//I use the Function Something like this in C#
IntPtr buffer = IntPtr.Zero;
int Count;
GetArrofStruct(ref Count,out buffer);
MyStruct[] arrayManaged = new MyStruct[Count];
for (int i = 0, nElemOffs = (int)buffer; i < Count; i++)
{
ru[i] = (MyStruct)Marshal.PtrToStructure((IntPtr)nElemOffs, typeof(MyStruct));
nElemOffs += Marshal.SizeOf(typeof(MyStruct));
}
在for循環中,第一元件被正確地編組,對於第二個元素,我得到一個AccessViolation。
在C++端數組似乎被正確填充(通過調試驗證)。
C++聲明非常荒謬,什麼是',* pnCnt'?無論如何,你無法直接使用它從C#中,無法釋放陣列的內存。 –
對不起,在C++聲明中* pnCnt實際上是* count。然後我在C#代碼的for循環之後使用Marshal.FreeCoTaskMem(buffer)釋放數組的內存。 – Karthik
有沒有任何答案可以解決您的問題? –