Marshal struct with array size fixed of other struct (MyStruct[X])


C

Cyril

Hello,

I have a problem to marshal a structure that contains an array of an
others struct. This array is an array size fixed (MyStruct[2] myStructs

and not MyStruct *myStructs).
For example :

C declaration :
struct Point {
int x;
int y;
}

struct Line {
Point[2] points;
int id;
}


For the C# declaration, I have try this declaration but this don't work
:
[StructLayout(LayoutKind.Explicit)]

public struct Point
{
[FieldOffset(0)] public int x;
[FieldOffset(4)] public int y;
}

[StructLayout(LayoutKind.Explicit)]
public struct Line
{
[FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst=2)]
public Point[] points;
[FieldOffset(8)] public int id;
}

I have try other declaration but I haven't find solution.
If you have solution or some councils please tell me.

Thanks,
Cyril


PS : You can send the VB.Net solution too... :)
 
Ad

Advertisements

N

Nicholas Paldino [.NET/C# MVP]

Cyril,

There are a few ways to go about this. First, let's use the Point
structure from the System.Drawing namespace (in System.Drawing.dll). It has
the same structure that you have, in the same layout. There is no need to
reinvent the wheel =)

Now, let's clean up your Line structure:

[StructLayout(LayoutKind.Sequential)]
public struct Line
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public Point[];
public int Id;
}

Now, since you only have two points, you could actually declare it like
this:

[StructLayout(LayoutKind.Sequential)]
public struct Line
{
public Point StartPoint;
public Point EndPoint;
public int Id;
}

Assuming that the pack size is four, this should work just fine.

Those should work for you. You should only use FieldOffset when you
know that a field will be interpreted different ways (as in a union).

Hope this helps.
 
Ad

Advertisements

C

Cyril

Thanks for your answer but here Point struct are an example to explain
my probleme. I use some personnal struct but to simplify the question I
have create an example with simple struct and an array of 2 Point.But
in fact my array have more structs in array.

So if you have a solution???
this solution ([MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)])
work fine with simple type but not with user struct define.
Cyril
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top