Need to call C++ dll from C#

  alignment, c++, marshalling, memory

I have the following C++ code:

   DLLExport int _CDECL nncpu_evaluate_incremental(
  int player, int* pieces, int* squares, NNCPUdata** nncpu)
{
  assert(nncpu[0] && uint64_t(&nncpu[0]->accumulator) % 64 == 0);

  Position pos;
  pos.nncpu[0] = nncpu[0];
  pos.nncpu[1] = nncpu[1];
  pos.nncpu[2] = nncpu[2];
  pos.player = player;
  pos.pieces = pieces;
  pos.squares = squares;
  return nncpu_evaluate_pos(&pos);
}

using this datastructure

typedef struct DirtyPiece {
  int dirtyNum;
  int pc[3];
  int from[3];
  int to[3];
} DirtyPiece;

typedef struct Accumulator {
#if defined(USE_FLOAT)
  alignas(64) float accumulation[2][256];
#else
  alignas(64) int16_t accumulation[2][256];
#endif
  int computedAccumulation;
} Accumulator;

typedef struct NNCPUdata {
  Accumulator accumulator;
  DirtyPiece dirtyPiece;
} NNCPUdata 

I have the same kind of struct hierarchy defined in C#, but if I call the code it always fails on the assert. To be more specific it fails on the second part of the assert
assert(nncpu[0] && uint64_t(&nncpu[0]->accumulator) % 64 == 0); which is a check if the memory is properly aligned.

  [StructLayout(LayoutKind.Sequential, Pack =64)]
public  unsafe struct Accumulator
{
    public int[] accumulation;
    public int computedAccumulation;
    public Accumulator(int state)
    {
        accumulation = new int[512];
        computedAccumulation = state;
    }
}

Can somebody point me to the solution, or some good reading material regarding this problem?
thanks
JB

Source: Windows Questions C++

LEAVE A COMMENT