I call a C routine from C#, with some doubles, ints, a large string and some arrays as argument. Some arrays return correctly, with the correct values, only one array does not.The array is corrupted on returning to C#, NOT during execution of the C-routine.
C#-side:
[DllImport(@"Critias.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "Cr",
CharSet = CharSet.Ansi, BestFitMapping =false,ThrowOnUnmappableChar =true)]
public static extern int Cr([In] StringBuilder isc,
int nrModes,
double[] eigenfrequencies,
ref double error,
double[,] defl,
double[] reactions,
double[,] force);
public double[,] Deflection;
public double[,] MemberEndforces;
public double[] Reactions;
public double error;
....
var eigenFreq = new double[nrModes + 1]; // +1 for C-sides pseudo FORTRAN arrays
MemberEndforces = new double[mbCount,12];
Deflection = new double[mbCount + 1,6];
Reactions = new double[6];
info = NativeMethods.Cr(
isc, nrModes, eigenFreq, ref error, Deflection, Reactions, MemberEndforces);
now, all arguments come back OK, except MemberEndforces. Also when I swap the order of Reactions and MemberEndforces on the caller AND callee-side, Reactions come back from Cr OK, but not MemberEndforces. I get "Unable to read memory" for MemberEndforces, in the VS watch pannel . Also, if I do NOT fill MemberEndforces C-side, so do nothing with it, it makes no difference: Still the same error message
And C-side:
extern "C"
{
__declspec(dllexport) int __cdecl Cr(
char *_isc,
int nM_calc,
double* f,
double* error,
double* deflection,
double* reactions ,
double* endforces ) // this is the annoying one
{
double** Q; // malloc-ed somewhere.
double* D;
double *R;
.....
for (int ii = 0; ii < DoF; ii++)
deflection[ii ] = D[ii+1];
for (int ii = 0; ii < nE; ii++)
for (int jj = 0; jj < 12; jj++)
{
endforces[ii * 12 + jj] = Q[ii+1][jj + 1];// values OK,but...
}
for (int ii = 0; ii < 6; ii++)
reactions[ii] = R[ii+1];
......
}
The question, of course, is: What do I do wrong (and why, maybe?)?