472,805 Members | 1,209 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,805 software developers and data experts.

Three Ways to Marshal Data - Which is best?

I have operation within a class that marshals the data into a byte
array. Below are three different ways that work. Are there any
downsides to using one over the the other?

public virtual byte[] ToRaw1()
{
byte[] byteArray = new byte[Size];
IntPtr pointer = Marshal.AllocHGlobal(Size);
Marshal.StructureToPtr(this, pointer, false);
Marshal.Copy(pointer, byteArray, 0, Size);
Marshal.FreeHGlobal(pointer);
return byteArray;
}

public virtual byte[] ToRaw2()
{
byte[] byteArray = new byte[Size];
IntPtr byteArrayPtr = Marshal.UnsafeAddrOfPinnedArrayElement
(byteArray, 0);
Marshal.StructureToPtr(this, byteArrayPtr, false);
return byteArray;
}

public virtual byte[] ToRaw3()
{
byte[] byteArray = new byte[Size];
unsafe
{
fixed (byte* pData = byteArray)
{
Marshal.StructureToPtr(this, (IntPtr)pData, false);
}
}
return byteArray;
}
Nov 12 '08 #1
2 15731
Well, #2 is incorrect in that you aren't pinning the array before
passing it to UnsafeAddrOfPinnedArrayElement.

#1 is going to leak memory if an exception is thrown before the call to
FreeHGlobal.

Generally though, I would say not to use any of these. You should use
Serialization or DataContracts instead. You are marshalling in .NET, not to
unmanaged code (else, why have the byte array) and you want to go from .NET
to .NET, not from .NET to unmanaged code.

Otherwise, why have it in a byte array?

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"O.B." <fu******@bellsouth.netwrote in message
news:f3**********************************@l33g2000 pri.googlegroups.com...
>I have operation within a class that marshals the data into a byte
array. Below are three different ways that work. Are there any
downsides to using one over the the other?

public virtual byte[] ToRaw1()
{
byte[] byteArray = new byte[Size];
IntPtr pointer = Marshal.AllocHGlobal(Size);
Marshal.StructureToPtr(this, pointer, false);
Marshal.Copy(pointer, byteArray, 0, Size);
Marshal.FreeHGlobal(pointer);
return byteArray;
}

public virtual byte[] ToRaw2()
{
byte[] byteArray = new byte[Size];
IntPtr byteArrayPtr = Marshal.UnsafeAddrOfPinnedArrayElement
(byteArray, 0);
Marshal.StructureToPtr(this, byteArrayPtr, false);
return byteArray;
}

public virtual byte[] ToRaw3()
{
byte[] byteArray = new byte[Size];
unsafe
{
fixed (byte* pData = byteArray)
{
Marshal.StructureToPtr(this, (IntPtr)pData, false);
}
}
return byteArray;
}

Nov 12 '08 #2
Good call on #1. #3 is also seems to better than #1 in that it
doesn't allocate an additional buffer of memory.

I've corrected #2 as follows to pin the address first.
public virtual byte[] ToRaw2()
{
byte[] byteArray = new byte[Size];
GCHandle byteArrayPtr = GCHandle.Alloc(byteArray,
GCHandleType.Pinned);
Marshal.StructureToPtr(this, byteArrayPtr.AddrOfPinnedObject(),
false);
return byteArray;
}

However, I can't determine if #2 or #3 is better. Thoughts?

As for converting the data to a byte array, I have a structure that
serves as a generic data handler between our application and other
applications. This structure has the smarts to determine whether the
data is to be sent through an Internet socket, a COM object, or
another .NET application). To keep it generic, the interface requires
a byte array of the data being sent and received. In addition, the
data conversion to a byte array must be as fast as possible, so as to
maintain real-time operation. It has been my observation that
Marshal.StructureToPtr is faster than manually marshaling the data
into a byte array.

On Nov 12, 1:06*pm, "Nicholas Paldino [.NET/C# MVP]"
<m...@spam.guard.caspershouse.comwrote:
* * Well, #2 is incorrect in that you aren't pinning the array before
passing it to UnsafeAddrOfPinnedArrayElement.

* * #1 is going to leak memory if an exception is thrown before the call to
FreeHGlobal.

* * Generally though, I would say not to use any of these. *You should use
Serialization or DataContracts instead. *You are marshalling in .NET, not to
unmanaged code (else, why have the byte array) and you want to go from .NET
to .NET, not from .NET to unmanaged code.

* * Otherwise, why have it in a byte array?

--
* * * * * - Nicholas Paldino [.NET/C# MVP]
* * * * * - m...@spam.guard.caspershouse.com

"O.B." <funkj...@bellsouth.netwrote in message

news:f3**********************************@l33g2000 pri.googlegroups.com...
I have operation within a class that marshals the data into a byte
array. *Below are three different ways that work. *Are there any
downsides to using one over the the other?
public virtual byte[] ToRaw1()
{
*byte[] byteArray = new byte[Size];
*IntPtr pointer = Marshal.AllocHGlobal(Size);
*Marshal.StructureToPtr(this, pointer, false);
*Marshal.Copy(pointer, byteArray, 0, Size);
*Marshal.FreeHGlobal(pointer);
*return byteArray;
}
public virtual byte[] ToRaw2()
{
*byte[] byteArray = new byte[Size];
*IntPtr byteArrayPtr = Marshal.UnsafeAddrOfPinnedArrayElement
(byteArray, 0);
*Marshal.StructureToPtr(this, byteArrayPtr, false);
*return byteArray;
}
public virtual byte[] ToRaw3()
{
*byte[] byteArray = new byte[Size];
*unsafe
*{
* *fixed (byte* pData = byteArray)
* *{
* * *Marshal.StructureToPtr(this, (IntPtr)pData, false);
* *}
*}
*return byteArray;
}
Nov 12 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Michael McGarry | last post by:
Hi, I am using the marshal module in python to save a data structure to a file. It does not appear to be portable. The data is saved on a Linux machine. Loading that same data on a Mac gives me...
1
by: _DD | last post by:
Existing problem: A function that runs on a thread needs to return data to the UI thread. When the data is returned, that will trigger secondary tasks, including access to form controls and...
2
by: Anthony Biondo Jr | last post by:
I am trying to figure out the best way to return data through a web service. If the value is a single value I can just set it equal to the web service name. If I am returning a set of data I have...
0
by: jacuna | last post by:
the three ways to return control from a called function to a caller are:
5
by: TiNo | last post by:
Hi, I have installed python two days ago on a USB memory stick (I am on the move and have no laptop.) I am on windows computers, mostly XP, all the time. Now, after pluging it in to a...
6
by: Immortal Nephi | last post by:
First class is the base class. It has two data: m_Base1 and m_Base2. Second class and third class are derived classes and they are derived from first class. m_Base1 and m_Base2 are inherited into...
1
by: oldyork90 | last post by:
I have two sets of text strings. They are related to each other and are not proprietary. X group contains about 2000 short, one to three word, strings. Y contains about 50. These two groups...
0
by: raylopez99 | last post by:
Inspired by Jon, I did a demo prorgram showing three ways to declare predicates, in for example the "FindIndex" and "FindLastIndex" methods of Lists, but in general you can do this for any...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.