passing a struct by ref to unmanged code

  • Thread starter Thread starter codymanix
  • Start date Start date
C

codymanix

i want to pass a struct by reference to a function in a c++ dll.

the problem is that the call causes an ArgumentException in the calling c#
code.
i already tried to use "out" instead of "ref" there was no exception
generated but i
saw in the unmanaged code all fields of the struct were uninitialized!
this is my c# code:

[StructLayout(LayoutKind.Sequential,Pack=1)]
struct WorldStats
{
public ObjectStats[] stats;
public int iterations;
public int living;
public WorldStats(int n)
{
stats = new ObjectStats[n];
iterations=0;
living=0;
}
}

[DllImport("aikernel.dll", CallingConvention=CallingConvention.Winapi)]
static extern void GetWorldStats(ref WorldStats ws);

WorldStats ws = new WorldStats(this.MAXOBJECTS);
GetWorldStats(ref ws); // here is the argumentexception thrown


the function in my c++ dll is declared as follows:
__declspec(dllexport) void /*WINAPI*/__stdcall GetWorldStats(WorldStats &
ws);

#pragma pack(push,1)
struct WorldStats
{
ObjectStats * stats;
int iterations;
int living;
};
#pragma pack(pop,1)
 
[StructLayout(LayoutKind.Sequential,Pack=1)]
struct WorldStats
{
public ObjectStats[] stats;
public int iterations;
public int living;


The exception is likely caused by the stats member. You can't declare
it as an array, it will not marshal correctly. Try making it an IntPtr
instead, and handle the array allocation and initialization yourself.



Mattias
 
Back
Top