all groups > dotnet clr > september 2003 >
You're in the

dotnet clr

group:

passing a struct by ref to unmanged code


passing a struct by ref to unmanged code codymanix
9/22/2003 11:36:32 PM
dotnet clr: 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)

--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk


Re: passing a struct by ref to unmanged code Mattias Sjögren
9/23/2003 2:10:16 AM

[quoted text, click to view]


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

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
AddThis Social Bookmark Button