並感謝任何幫助的建議。Interop的問題C#/ C:AccessViolationException
我在C這平凡函數:
__declspec(dllexport) Point* createPoint (int x, int y) {
Point *p;
p = (Point*) malloc(sizeof(Point));
p->x = x;
p->y=y;
return p;
}
點是一個非常簡單的結構具有兩個int字段,x和y。
我想從C#調用這個函數。
我用這個代碼:
[DllImport("simpleC.dll", EntryPoint = "createPoint", CallingConvention = CallingConvention.Cdecl, SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.LPStruct)]
public static extern Point createPoint(int x, int y);
Point p = Wrapper.createPoint(1, 2);
但在運行時我有一個AccessViolationException
。詳細觀察異常,我發現從Marshal.CoTaskMemFree(IntPtr)
方法拋出異常。
看來這種方法無法釋放C malloc分配的內存。
我在做什麼錯了?
真的很感謝。
非常感謝,您澄清我的任何想法!我的目標是將正則表達式的pcre C llibrary整合到C#中),然後返回很多malloc和sruct指針。 現在我正在使用第二種解決方案,它可以工作,但它很難釋放內存(應該寫C函數釋放器),但是我喜歡第二種解決方案,並且會實現它!非常感謝! – 2010-12-19 07:09:16