简体   繁体   中英

problems importing a C++ dll

I am trying to access this C++ function from the C# code in my program

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];

}

The call is as shown below

tred2(tensor, eigenValues, eigenVectors);

where tensor is float[,] and eigenvalues and eigenvectors are float[] arrays.

When i try doing this i get an exception

Access violation reading location 0x3f5dce99

when i try accessing

float a = mat[0][0]

What could be happening?

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

mat is a double-pointer type (pointer to pointer). In C#, float[,] is not a double-pointer. It's just syntactic sugar for accessing a multi-dimensional array, just like you would do mat[x + y * width] instead of mat[y][x] ;

In other words, you are passing a float* to your C++ application, not a float** .

You should change the way you use mat to access elements using the manual offset, like mat[y + 2 * x]

Either mat or mat[0] is a bad pointer. The problem lies in the code that allocates mat .

You need to first allocate an array with 3 pointers that can be done using a class:

class Pointer3
{
     IntPtr p1, p2, p3;
}

then you need to define a row using a class:

class Row3
{
     float a, b, c;
}

all that in C#. then you need to allocate them:

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);

Now its safe to call the function using matPtr as the matrix.
To get the values out of the modified matrix:

Marshal.PtrToStructure(matPtr, mat);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM