efficient way of casting structure and class instances to char*

R

raza

In C++ we can do things like (Header is an instance of C++ structure)

Send(m_Sock,(char*)&Header,sizeof(Header),0)

in C# we have Socket.Send(byte[] , int offset, int size, flags)

how do i convert the instance of a C# class or strucute to byte array
efficiently rathen then creating function myself todo that ?

Regards
 
E

Eric Gunnerson [MS]

Raza,

If unsafe code is okay okay with you, you can do something like:

byte[] buffer = new byte[sizeof(Header)];

fixed (byte* pBuffer = buffer)
{
Header* pHeader = (Header*) pBuffer;

// set fields of pHeader here.
}

You might also find something useful in the Marshal class.


--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://weblogs.asp.net/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
 
B

BMermuys

raza said:
In C++ we can do things like (Header is an instance of C++ structure)

Send(m_Sock,(char*)&Header,sizeof(Header),0)

in C# we have Socket.Send(byte[] , int offset, int size, flags)

how do i convert the instance of a C# class or strucute to byte array
efficiently rathen then creating function myself todo that ?

Regards

[StructLayout(LayoutKind.Sequential)]
public struct Header
{
public int i;
...
...
}

// create header and setup
Header header = new Header();
....

// determine struct size
int size = Marshal.SizeOf( typeof(Header) );

// create byte-array
byte[] buffer = new byte[size];

// pin the byte array
GCHandle hBuffer = GCHandle.Alloc( buffer, GCHandleType.Pinned );

// marshal struct into the byte array
Marshal.StructToPtr( header, hBuffer.AddrOfPinnedObject(), true );

// free pinning
hBuffer.Free();

// now you can send the buffer
Send( buffer, 0, size, flags );


HTH,
greetings
 

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