2011-05-17 79 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);