struct memory layout

J

jconnell

I want to make a struct in C# that has binary compatibility with an
existing struct in C++, so I can use C++.NET to do memcpy() transfers
from a binary stream onto some structs in C#. I can't seem to figure
out how to make this work.

// C++
struct st
{
int a;
int b;
char c[100];
int d;
}

// C#
[StructLayout(LayoutKind.Sequential)]
struct st
{
public int a;
public int b;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
public string c;
public int d;
}

So there is a very specific byte layout in C++ that I have to use
(external constraint) and being able to memcpy the 112 bytes onto my
struct for speed purposes is hugely important. This works for ints
and non-array struct members, but when I add any kind of array, I'm
hosed. The MarshalAs attribute was mostly just a first stab at
getting this right, but I've tried a few other ideas--none work.

By the way, the string doesn't need to be a string. It could be a
fixed array of 100 chars... I just can't have

public char char0;
public char char1;
public char char2;
etc...

Anyone know how to make this work?

TIA,
Jesse
 
L

Lav G

The correct layout would be

[StructLayout(LayoutKind.Sequential)]
struct st
{
public int a;
public int b;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
public byte[] c;
public int d;
}

Lav G
http://lavbox.blogspot.com
 
P

Peter Morris

Not my area at all, but I have seen StringBuilder used for buffers, so try
this

[StructLayout(LayoutKind.Sequential)]
struct st
{
public int a;
public int b;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
public StringBuilder c;
public int d;
}
 
J

Jesse C

That seems more correct, but still doesn't do the trick. On the C++
side, all 4 struct members are 4 bytes and the struct is 16 bytes
total.
 
D

Doug Forster

Well also not my area but this returns the correct size:

[StructLayout(LayoutKind.Sequential)]
struct st
{
public int a;
public int b;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)]
public char[] c;
public int d;
}
............
private void button1_Click(object sender, EventArgs e) {
st a = new st();
MessageBox.Show(Marshal.SizeOf(a).ToString());
}

Cheers
Doug Forster


That seems more correct, but still doesn't do the trick. On the C++
side, all 4 struct members are 4 bytes and the struct is 16 bytes
total.
 

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