2011-05-17 78 views
0

我想從C#代碼中訪問這個C++函數在我的計劃問題導入C++ DLL

Tridiagonal3 (float** mat, float* diag, float* subd) 
{ 
    float a = mat[0][0], b = mat[0][1], c = mat[0][2], 
         d = mat[1][1], e = mat[1][2], 
             f = mat[2][2]; 

} 

是如下圖所示

tred2(tensor, eigenValues, eigenVectors); 

其中張量float[,]和特徵值的呼叫和特徵向量是float[]陣列。

當我嘗試這樣做,我得到一個異常

Access violation reading location 0x3f5dce99 

,當我嘗試訪問

float a = mat[0][0] 

可能是什麼回事?

+0

您作爲參數傳入了什麼內容?它看起來像數組尚未分配。 – DanDan 2011-05-17 16:07:47

+0

你爲什麼不發佈呼叫站點代碼?順便說一句'float [,]'是什麼? – Nawaz 2011-05-17 16:09:25

+0

@Nawaz:'float [,]'是C#中的一個多維數組。 – 2011-05-17 16:10:48

回答

5

Tridiagonal3 (float** mat, float* diag, float* subd)

墊是雙指針類型(指向指針)。 在C#中,float [,]是而不是的雙指針。這只是用於訪問多維數組的語法糖,就像您要做的那樣,不是mat[y][x]而是mat[x + y * width];

換句話說,您將float*傳遞給您的C++應用程序,而不是float**

你應該改變你使用mat使用手動偏移訪問元素,您需要先用3個指針,可以使用一個類來完成分配數組的方式,像mat[y + 2 * x]

0

matmat[0]是一個糟糕的指針。問題在於分配mat的代碼。

0

class Pointer3 
{ 
    IntPtr p1, p2, p3; 
} 

,那麼你需要使用一個類定義行:

class Row3 
{ 
    float a, b, c; 
} 

個都在C#中。那麼你需要對其進行分配:

Row3 row1, row2, row3; 
// todo: init values 
Pointer3 mat; 
// allocate place for the rows in the matrix 
mat.p1 = Marshal.AllocHGlobal(sizeof(Row3)); 
mat.p2 = Marshal.AllocHGlobal(sizeof(Row3)); 
mat.p3 = Marshal.AllocHGlobal(sizeof(Row3)); 
// store the rows 
Marshal.StructureToPtr(row1, mat.p1, false); 
Marshal.StructureToPtr(row2, mat.p2, false); 
Marshal.StructureToPtr(row3, mat.p3, false); 
// allocate pointer for the matrix 
IntPtr matPtr = Marshal.AllocHGlobal(sizeof(Pointer3)); 
// store the matrix in the pointer 
Marsha.StructureToPtr(mat, matPtr, false); 

現在它安全地調用使用matPtr爲基質的功能。
要從修改後的矩陣中獲取數值:

Marshal.PtrToStructure(matPtr, mat);