Calling from C# to C function which accept a struct array allocated by caller

Posted by lifey on Stack Overflow See other posts from Stack Overflow or by lifey
Published on 2011-01-02T07:45:19Z Indexed on 2011/01/02 7:53 UTC
Read the original article Hit count: 201

Filed under:
|

I have the following C struct

struct XYZ
{
void            *a;
char            fn[MAX_FN];     
unsigned long   l;          
unsigned long   o;  
};

And I want to call the following function from C#:

extern "C"  int     func(int handle, int *numEntries, XYZ *xyzTbl);

Where xyzTbl is an array of XYZ of size numEntires which is allocated by the caller

I have defined the following C# struct:
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Ansi)] public struct XYZ { public System.IntPtr rva; [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 128)] public string fn; public uint l; public uint o; }

and a method:

 [System.Runtime.InteropServices.DllImport(@"xyzdll.dll", 
     CallingConvention = CallingConvention.Cdecl)]
 public static extern Int32 func(Int32 handle, ref Int32 numntries,
     [MarshalAs(UnmanagedType.LPArray)] XYZ[] arr);

Then I try to call the function :

XYZ xyz = new XYZ[numEntries];
for (...) xyz[i] = new XYZ();
func(handle,numEntries,xyz);

Of course it does not work. Can someone shed light on what I am doing wrong ?

© Stack Overflow or respective owner

Related posts about c#

Related posts about marshalling