Struct Socket C#

T

Tolga Ongunsu

I want to send the struct to another Program by using TcpClient. I found a
method that converts struct to byte but it doesnot working correctly. What
am i missing?


[StructLayout(LayoutKind.Sequential)]
public struct student
{
[MarshalAs(UnmanagedType.ByValArray,SizeConst=33)]
public char[] sName;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 33)]
public char[] sLastName;
}



private byte[] StructureToByteArray(object obj)
{
int len = Marshal.SizeOf(obj);
byte[] arr = new byte[len];
IntPtr ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(obj, ptr, true);
Marshal.Copy(ptr, arr, 0, len);
Marshal.FreeHGlobal(ptr);
return arr;
}
 
A

Arne Vajhøj

Tolga said:
I want to send the struct to another Program by using TcpClient. I found
a method that converts struct to byte but it doesnot working correctly.
What am i missing?

You can start by giving a more specific description of how it is not
working correctly.

Arne
 
T

Tolga Ongunsu

This result of mine
DataLen:66sName:Tolga Ongunsu
‡cv€’hvÔı¯sLastName:Ongunsu ‡cv€’hvÔı¯

Corrent one has to be
DataLen:66sName:TolgasLastName:Ongunsu
 
A

Arne Vajhøj

Tolga said:
This result of mine
DataLen:66sName:Tolga Ongunsu
‡cv€’hvÔı¯sLastName:Ongunsu ‡cv€’hvÔı¯

Corrent one has to be
DataLen:66sName:TolgasLastName:Ongunsu

The result you get looks correct to me because:

[MarshalAs(UnmanagedType.ByValArray,SizeConst=33)]
public char[] sName;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 33)]
public char[] sLastName;

tell that the fields are 33 long, so some kind of padding should
happen.

Arne
 

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