473,698 Members | 2,281 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Marshal Not Copying all Data to Fixed Byte Array

When using Marshal to copy data from a byte array to the structure
below, only the first byte of the "other" array is getting copied from
the original byte array. What do I need to specify to get
Marshal.PtrToSt ructure to copy the all the data into the "other"
array?
[StructLayout(La youtKind.Explic it, Size = 40)]
unsafe public struct DeadReckoning
{
[FieldOffset(0)]
public byte algorithm; // 1 byte

[FieldOffset(1)]
public fixed byte other[15]; // 15 bytes

[FieldOffset(16)]
public Vector linearAccelerat ion; // 12 bytes

[FieldOffset(28)]
public Vector angularVelocity ; // 12 bytes
}
}

// Given rawData as a byte array
DeadReckoning dr = new DeadReckoning() ;
IntPtr pData = Marshal.AllocHG lobal(40);
Marshal.Copy(ra wData, 28, pData, 40);
Marshal.PtrToSt ructure(pData, dr);
Marshal.FreeHGl obal(pData);

At this point, only dr.other[0] has the correct value; the values at
1-14 indexes of dr.other are not set.

Jul 11 '08 #1
2 7201
O.B. wrote:
When using Marshal to copy data from a byte array to the structure
below, only the first byte of the "other" array is getting copied from
the original byte array. What do I need to specify to get
Marshal.PtrToSt ructure to copy the all the data into the "other"
array?
[StructLayout(La youtKind.Explic it, Size = 40)]
unsafe public struct DeadReckoning
{
[FieldOffset(0)]
public byte algorithm; // 1 byte

[FieldOffset(1)]
public fixed byte other[15]; // 15 bytes

[FieldOffset(16)]
public Vector linearAccelerat ion; // 12 bytes

[FieldOffset(28)]
public Vector angularVelocity ; // 12 bytes
}
}
What's "Vector"? A structure of 12 bytes?
// Given rawData as a byte array
DeadReckoning dr = new DeadReckoning() ;
IntPtr pData = Marshal.AllocHG lobal(40);
Marshal.Copy(ra wData, 28, pData, 40);
Because you're using an unsafe struct with explicit layout, there's actually
no need to use copying and marshalling at all. You can just write

DeadReckoning dr;
unsafe {
fixed (byte* pData = &rawData[28]) {
dr = *((DeadReckonin g*) pData);
}
}

With this approach, however, you have to verify that "rawData" holds enough
bytes to populate the structure, or it'll copy garbage from the stack. If
you're lucky.
Marshal.PtrToSt ructure(pData, dr);
This shouldn't work, or at least, it doesn't for me. It throws
ArgumentExcepti on because "dr" is a structure. This overload is for classes;
for structures, the right syntax would be

DeadReckoning dr = (DeadReckoning) Marshal.PtrToSt ructure(pData,
typeof(DeadReck oning));

--
J.
Jul 11 '08 #2
On Jul 11, 3:40 pm, Jeroen Mostert <jmost...@xs4al l.nlwrote:
O.B. wrote:
When using Marshal to copy data from a byte array to the structure
below, only the first byte of the "other" array is getting copied from
the original byte array. What do I need to specify to get
Marshal.PtrToSt ructure to copy the all the data into the "other"
array?
[StructLayout(La youtKind.Explic it, Size = 40)]
unsafe public struct DeadReckoning
{
[FieldOffset(0)]
public byte algorithm; // 1 byte
[FieldOffset(1)]
public fixed byte other[15]; // 15 bytes
[FieldOffset(16)]
public Vector linearAccelerat ion; // 12 bytes
[FieldOffset(28)]
public Vector angularVelocity ; // 12 bytes
}
}

What's "Vector"? A structure of 12 bytes?
// Given rawData as a byte array
DeadReckoning dr = new DeadReckoning() ;
IntPtr pData = Marshal.AllocHG lobal(40);
Marshal.Copy(ra wData, 28, pData, 40);

Because you're using an unsafe struct with explicit layout, there's actually
no need to use copying and marshalling at all. You can just write

DeadReckoning dr;
unsafe {
fixed (byte* pData = &rawData[28]) {
dr = *((DeadReckonin g*) pData);
}
}

With this approach, however, you have to verify that "rawData" holds enough
bytes to populate the structure, or it'll copy garbage from the stack. If
you're lucky.
Marshal.PtrToSt ructure(pData, dr);

This shouldn't work, or at least, it doesn't for me. It throws
ArgumentExcepti on because "dr" is a structure. This overload is for classes;
for structures, the right syntax would be

DeadReckoning dr = (DeadReckoning) Marshal.PtrToSt ructure(pData,
typeof(DeadReck oning));

--
J.
My bad. I was trying to trim down the post. The DeadReckoning
structure is declared within a ExplicitLayout class (see below). The
explicit constructor outlines the call to marshalling data from an
array to the class structure.

namespace DIS
{
[StructLayout(La youtKind.Explic it)]
public class EntityState
{
[FieldOffset(0)]
public Header header; // 12 bytes

[FieldOffset(12)]
public EntityIdentifie r entityID; // 6 bytes

[FieldOffset(18)]
public ForceIdentifier forceID; // 1 byte

[FieldOffset(19)]
public byte numArticulation s; // 1 byte

[FieldOffset(20)]
public EntityType type; // 8 bytes

[FieldOffset(28)]
public EntityType altType; // 8 bytes

[FieldOffset(36)]
public Vector linearVelocity; // 12 bytes

[FieldOffset(48)]
public WorldCoordinate location; // 24 bytes

[FieldOffset(72)]
public EulerAngles orientation; // 12 bytes

[FieldOffset(84)]
public Appearance appearance; // 4 bytes

[FieldOffset(88)]
public DeadReckoning deadReckoning = new DeadReckoning() ; //
40 bytes

[FieldOffset(128 )]
public EntityMarking marking; // 12 bytes

[FieldOffset(140 )]
public Unsigned32 capabilities; // 4 bytes

[MarshalAs(Unman agedType.ByValA rray, ArraySubType =
UnmanagedType.S truct)]
[FieldOffset(144 )]
public Articulation[] articulations; // 16 bytes each

public EntityState() { }

public EntityState(byt e[] rawData)
{
// Copy the first 144 bytes to determine if there are
articulations.
unsafe
{
if (rawData.Length <= 144)
{
fixed (byte* pData = rawData)
{
Marshal.PtrToSt ructure((IntPtr ) pData, this);
}
}
else
{
int dataSize = rawData.Length 144 ? 144 :
rawData.Length;
IntPtr pData = Marshal.AllocHG lobal(dataSize) ;
Marshal.Copy(ra wData, 0, pData, dataSize);
Marshal.PtrToSt ructure(pData, this); // Throws
exception
Marshal.FreeHGl obal(pData);
}
}

// If there are articulations, allocate more memory for
this class
// and copy remaining data into articulations array.
if (rawData.Length 144 && numArticulation s 0)
{
// Allocate memory for articulations
articulations = new Articulation[numArticulation s];

// Copy values for each articulation
byte[] tempArray = new byte[16];
for (int i = 0; i < numArticulation s; i++)
{
Array.Copy(rawD ata, 144 + i * 16, tempArray, 0,
16);
unsafe
{
fixed (byte* pData = tempArray)
{
articulations[i] =
(Articulation)M arshal.PtrToStr ucture((IntPtr) pData,
typeof(Articula tion));
}
}
}
}

header.length = (ushort)rawData .Length;
}

public byte[] ToRaw()
{
int pduSize = (int) header.length;
byte[] byteArray = new byte[pduSize];
IntPtr pointer = Marshal.AllocHG lobal(pduSize);
Marshal.Structu reToPtr(this, pointer, false);
Marshal.Copy(po inter, byteArray, 0, pduSize);
Marshal.FreeHGl obal(pointer);
return byteArray;
}
}
}

Jul 11 '08 #3

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

Similar topics

0
1895
by: William Stacey | last post by:
The following code works, but I can't figure out why. I take a struct with two members, a single byte and byte. I then marshal the whole struct to a byte. I create a new struct (without init'ing any members) and marshal the tmp array back to the new struct. The new struct shows the same data. The single type is easy, that just gets copied. The byte ref type is the interesting part. The address (i.e ref) of the original byte gets...
9
2813
by: Angel | last post by:
Hi again, I'm trying to call functions from a proprietary DLL but it's turned out to be more difficult than I thought. I have this W32.DLL which was written in C by USPS. They don't provide the code so I only have the documentation. I'm trying to call a function called z4date that, according to the docs, returns the date as "an 8-byte character string in the "YYYYMMDD" format". When I run it with this code I've written , I get "Can not...
1
4212
by: dhornyak | last post by:
I have been banging my head against the wall for a while now, and can't seem to id the problem. I've been through a ton of posts and the code doesn't seem any different. Can anybody see it? When I call to GetTokenInformation I receive a buffer size (see //HERE... comment in code), but when I let the code continue, asp.net just sits there returning nothing, apparently on the Marshal.AllocHGlobal call. Here's the library function:
2
4854
by: twawsico | last post by:
I have a piece of code that needs to read the contents of a binary file (that I've created with another app) into an array of structures. The binary data in the file represents just a series of singles that correspond to those in my structure detailed below. So when I load the file, all that I know for certain is that there will be some multiple of these eight singles represented in the binary data. My code below will read the data...
10
4990
by: David Fort | last post by:
Hi, I'm upgrading a VB6 app to VB.net and I'm having a problem with a call to a function provided in a DLL. The function takes the address of a structure which it will fill in with values. I get an error: ---------------- An unhandled exception of type 'System.NullReferenceException' occured in
4
11975
by: Rainer Queck | last post by:
Hi NG, is there a way to copy a buffer pointed to by a IntPtr directly into a two dimensional byte-array? I tried this, what obviously doesn't work: byte image = new byte; IntPtr p = <hardwareDeviceClass>.GetBufPtr();
2
7615
by: O.B. | last post by:
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?
1
6307
by: nicewenyan | last post by:
I want to pass a managed c# byte (8 bit) array into a unmanaged c++ function: extern "C" void AddData(unsigned int* data); I use P/Invoke on managed side to do the marshaling as following: public static extern int AddData(IntPtr data);
2
15933
by: O.B. | last post by:
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; IntPtr pointer = Marshal.AllocHGlobal(Size); Marshal.StructureToPtr(this, pointer, false); Marshal.Copy(pointer, byteArray, 0, Size);
0
8676
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
9161
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...
0
9029
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8867
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...
0
7732
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3050
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
2332
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2006
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.