Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

[StructLayoutAttribute(Sequential, CharSet = CharSet.Ansi)]
public struct XYZ
{
   public System.IntPtr rva;
   [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 128)]
   public string fn;
   public uint l;
   public uint o;
}

and a method:

 [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 ?

like image 751
lifey Avatar asked Dec 03 '25 06:12

lifey


1 Answers

[StructLayoutAttribute(Sequential, CharSet = CharSet.Ansi)]
public struct XYZ
{
   public System.IntPtr rva;
   [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 128)]
   public string fn;
   public uint l;
   public uint o;
}

Shouldn't those uint be ulong ? Also, MAX_FN is 128 right ?

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

XYZ is a value type (struct), so the second line here is redundant (structs are always initialized)

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

[MarshalAs(UnmanagedType.LPArray)] is redundant, the compiler will see it's a struct array.

like image 135
Ohad Schneider Avatar answered Dec 05 '25 22:12

Ohad Schneider