By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,465 Members | 1,501 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,465 IT Pros & Developers. It's quick & easy.

Structure to Byte Array - Which is better? Marshal Copy or FixedByte Assignment

P: n/a
I have a structure named EntityState with an explicit layout.
The following two operations exist within the class to return a byte
array representing the current object. Upon executing them each a
million times, I've learned that the ToRaw2() operation is twice as fast
as ToRaw().

So is it always safe to use the ToRaw2() operation or is there some gain
in using Marshal's Copy operation?
unsafe public byte[] ToRaw()
{
byte[] byteArray = new byte[EntityState.PDU_SIZE];
IntPtr pointer = Marshal.AllocHGlobal(EntityState.PDU_SIZE);
Marshal.StructureToPtr(this, pointer, false);
Marshal.Copy(pointer, byteArray, 0, EntityState.PDU_SIZE);
Marshal.FreeHGlobal(pointer);
return byteArray;
}

unsafe public byte[] ToRaw2()
{
byte[] byteArray = new byte[EntityState.PDU_SIZE];
fixed (byte* ptr = byteArray)
{
*((EntityState*)ptr) = this;
}
return byteArray;
}
Feb 4 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
>So is it always safe to use the ToRaw2() operation or is there some gain
in using Marshal's Copy operation?
ToRaw will handle a larger variety of structs. You can only use
pointers on a very restricted set of types in C#. But as long as it
works, it's fine to use ToRaw2.

If performance is your top priority then I guess ToRaw2 is the better
alternative. But I would also consider a third alternative that used
the BitConverter class to convert each member separately. The benefit
there is that the code doesn't require full trust to run.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Feb 4 '07 #2

P: n/a
On Feb 4, 6:21 am, Mattias Sjögren <mattias.dont.want.s...@mvps.org>
wrote:
So is it always safe to use the ToRaw2() operation or is there some gain
in using Marshal's Copy operation?

ToRaw will handle a larger variety of structs. You can only use
pointers on a very restricted set of types in C#. But as long as it
works, it's fine to use ToRaw2.

If performance is your top priority then I guess ToRaw2 is the better
alternative. But I would also consider a third alternative that used
the BitConverter class to convert each member separately. The benefit
there is that the code doesn't require full trust to run.
Ah, very good. Just making sure that I wasn't missing anything
obvious. I'm trying to run as close to real-time as possible. Thank
you for the prompt reply.

Feb 7 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.