2015-01-15 77 views
2

所以我試圖從一些c#代碼在dll中運行C++原生函數。而且,它的工作正常,但是,當我在我的函數調用中使用「出」我得到一個內存訪問衝突。這是什麼樣子:調用從c#本地c + +代碼與輸出參數

C#功能

[DllImport(pluginName)] 
public static extern IntPtr AddTriangleFixtuers(ShapeDef shapeDef, IntPtr toBody, ref Vector2 vertices, int triangleCount, Vector3 row1, Vector3 row2, out int fixtureCount); 

...

int test = 1; 
B2D.AddTriangleFixtuers(def, body.body, ref shapeTriangles[0], shapeTriangles.Length/3, firstRow, secondRow, out test); 

C++函數

EXTERN_DLL_EXPORT b2Fixture* __stdcall AddTriangleFixtuers(ShapeDef shapeDef, IntPtr* toBody, b2Vec2* vertices, int triangleCount, b2Vec3 row1, b2Vec3 row2, int& fixtureCount) { 
    fixtureCount = 0; 

    b2Fixture* lastFixture = NULL; 
    return lastFixture; 
} 

我最小的代碼突出問題,我正在跑進去。只要我嘗試在C++代碼中設置fixtureCount,就會發生以下錯誤:

An exception of type 'System.AccessViolationException' occurred in Assembly-CSharp.DLL but was not handled in user code Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

+1

您還必須添加P/Invoke定義('[DllImport]'等)。 – Luaan

+0

對不起,我忘了說明這個定義。現在編輯這個問題。 – Enzign

+0

可能重複:stackoverflow.com/questions/26992178/c-sharp-dllimport-with-pointers – Maher

回答

0

好吧,我終於明白了。這是導致內存訪問衝突的row1和row2。儘管我沒有在我的C++代碼中使用它們。我不得不以浮點形式發送x,y,z值來修復崩潰。

所以這是從Vector3轉換到b2Vec3這是問題。像Hans在評論中提到的那樣,問題不在於fixtureCount。