473,769 Members | 2,091 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.AllocHG lobal(Size);
Marshal.Structu reToPtr(this, pointer, false);
Marshal.Copy(po inter, byteArray, 0, Size);
Marshal.FreeHGl obal(pointer);
return byteArray;
}

public virtual byte[] ToRaw2()
{
byte[] byteArray = new byte[Size];
IntPtr byteArrayPtr = Marshal.UnsafeA ddrOfPinnedArra yElement
(byteArray, 0);
Marshal.Structu reToPtr(this, byteArrayPtr, false);
return byteArray;
}

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

#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.co m

"O.B." <fu******@bells outh.netwrote in message
news:f3******** *************** ***********@l33 g2000pri.google groups.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.AllocHG lobal(Size);
Marshal.Structu reToPtr(this, pointer, false);
Marshal.Copy(po inter, byteArray, 0, Size);
Marshal.FreeHGl obal(pointer);
return byteArray;
}

public virtual byte[] ToRaw2()
{
byte[] byteArray = new byte[Size];
IntPtr byteArrayPtr = Marshal.UnsafeA ddrOfPinnedArra yElement
(byteArray, 0);
Marshal.Structu reToPtr(this, byteArrayPtr, false);
return byteArray;
}

public virtual byte[] ToRaw3()
{
byte[] byteArray = new byte[Size];
unsafe
{
fixed (byte* pData = byteArray)
{
Marshal.Structu reToPtr(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.Pi nned);
Marshal.Structu reToPtr(this, byteArrayPtr.Ad drOfPinnedObjec t(),
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.Structu reToPtr is faster than manually marshaling the data
into a byte array.

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

* * #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.c om

"O.B." <funkj...@bells outh.netwrote in message

news:f3******** *************** ***********@l33 g2000pri.google groups.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.AllocHG lobal(Size);
*Marshal.Struct ureToPtr(this, pointer, false);
*Marshal.Copy(p ointer, byteArray, 0, Size);
*Marshal.FreeHG lobal(pointer);
*return byteArray;
}
public virtual byte[] ToRaw2()
{
*byte[] byteArray = new byte[Size];
*IntPtr byteArrayPtr = Marshal.UnsafeA ddrOfPinnedArra yElement
(byteArray, 0);
*Marshal.Struct ureToPtr(this, byteArrayPtr, false);
*return byteArray;
}
public virtual byte[] ToRaw3()
{
*byte[] byteArray = new byte[Size];
*unsafe
*{
* *fixed (byte* pData = byteArray)
* *{
* * *Marshal.Struct ureToPtr(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
6869
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 the bad marshal data message. Is this data really not portable or I am doing something wrong here. I thought the whole point of using Python and similar cross platform scripting languages to write once run everywhere, does that not hold
1
3030
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 lookup of data within a database. I'm not sure of the implications of using data returned by the thread within database access code, but I do know about InvokeRequired() etc for access to forms controls. I've used that often when individual...
2
1934
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 seen a couple ways to do this. The dataset coming back to me is a SybaseASE Data Reader. Any help you can provide would be much appreciated. thanks, Anthony Right now I have done the following:
0
1396
by: jacuna | last post by:
the three ways to return control from a called function to a caller are:
5
5244
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 different computer, I get the following message when I run pyhthon: 'import site' failed; use -v for traceback
6
2180
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 two derived classes. Second class has its own m_Base1 and m_Base2 and third class does the same. I am curious. How can second class and third class share the same m_Base1 and m_Base2? You define second class first and enter data into...
1
1293
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 supply the option items in two select boxes. Box Y scopes the items allowed in select box X. As selections in Y are made, optional items in X change. I’ve never hidden so much data before and wondered if there is a best way to do this. I...
0
1423
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 predicate. Note the most compact way is to use Lambda notation and anonymous functions, the first way shown below. The most 'intuitive' way is to 'hard code' the predicate using a predicate method, the second way shown below, but the best way (for me)...
0
9579
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10208
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9987
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9857
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7404
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5444
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3952
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3558
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2812
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.