473,657 Members | 2,625 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Marshal large byte array into array of structs?

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 correctly, but only marshals one
structure (8 singles) at a time, forcing me to loop through the binary
array in chunks. With the large amount of data I need to read, this is
very slow.

In C++, I can load data from the same file into an array of these
structures with a single call to fread() and it's very fast. Can anyone
give me a tip on how to accomplish this in .NET?

Thanks in advance.
Code that loads one struct at a time:

<StructLayout(L ayoutKind.Seque ntial)> Public Structure MyStruct
<MarshalAs(Unma nagedType.R4)> Dim X As Single
<MarshalAs(Unma nagedType.R4)> Dim Y As Single
<MarshalAs(Unma nagedType.R4)> Dim Z As Single
<MarshalAs(Unma nagedType.R4)> Dim tu As Single
<MarshalAs(Unma nagedType.R4)> Dim tv As Single
<MarshalAs(Unma nagedType.R4)> Dim NX As Single
<MarshalAs(Unma nagedType.R4)> Dim NY As Single
<MarshalAs(Unma nagedType.R4)> Dim NZ As Single
End Structure

Public Sub ReadBinaryIntoS tructArray(ByVa l FileName As String,
ByRef ArrayOfStructs( ) As MyStruct)
Dim bFileOpen As Boolean = False
Dim bHeapAlloc As Boolean = False
Dim fstm As FileStream
Dim binaryData() As Byte
Dim bytesRead As Long
Dim iStructSize As Int32
Dim iCurVertNum As Int32
Dim ptrTarget As IntPtr
Dim oSingleStruct As Object
Try
fstm = New FileStream(File Name, FileMode.Open,
FileAccess.Read , FileShare.Read)
bFileOpen = True
binaryData = New Byte(fstm.Lengt h - 1) {}
bytesRead = fstm.Read(binar yData, 0, CInt(fstm.Lengt h))
iStructSize = Marshal.SizeOf( GetType(MyStruc t))
ArrayOfStructs = New MyStruct(CInt(f stm.Length /
iStructSize) - 1) {}
'Until I can find a better bulk-copy method, we must load
one vert (8 singles) at a time).
iCurVertNum = 0
ptrTarget = Marshal.AllocHG lobal(iStructSi ze)
bHeapAlloc = True
For iCurVertNum = 0 To ArrayOfStructs. Length - 1

Marshal.Copy(bi naryData, iCurVertNum * iStructSize,
ptrTarget, iStructSize)
oSingleStruct = Marshal.PtrToSt ructure(ptrTarg et,
GetType(MyStruc t))

ArrayOfStructs( iCurVertNum).X = oSingleStruct.X
ArrayOfStructs( iCurVertNum).Y = oSingleStruct.Y
ArrayOfStructs( iCurVertNum).Z = oSingleStruct.Z
ArrayOfStructs( iCurVertNum).tu = oSingleStruct.t u
ArrayOfStructs( iCurVertNum).tv = oSingleStruct.t v
ArrayOfStructs( iCurVertNum).NX = oSingleStruct.N X
ArrayOfStructs( iCurVertNum).NY = oSingleStruct.N Y
ArrayOfStructs( iCurVertNum).NZ = oSingleStruct.N Z
Next
Marshal.FreeHGl obal(ptrTarget)
bHeapAlloc = False
Catch ex As System.OutOfMem oryException
Throw ex
Catch e As Exception
Throw e
Finally
If bFileOpen Then
fstm.Close()
End If
fstm = Nothing
If bHeapAlloc Then
Marshal.FreeHGl obal(ptrTarget)
End If
End Try
End Sub

Nov 21 '05 #1
2 4851
Does anyone at least know whether or not this is going to be possible
in VB.NET?

Thanks again.

Nov 21 '05 #2
Ok, now realizing that this thread would prob be more appropriate for
the Interop group, I've come up with a solution that seems to work fine
and loads/copies a couple of hundred thousand structures into the array
about as fast as my C++ version (well under a second).

Here's the bulk solution, which (typically) ended up being much
shorter/easier once I got on the right track.

Public Sub ReadBinaryTerra inData(ByVal FileName As String, ByRef
ArrayOfStructs( ) As MyStruct)
Dim bFileOpen As Boolean = False
Dim fstm As FileStream
Dim binaryData() As Byte
Dim bytesRead As Long
Dim iStructSize As Int32
Dim prtMyStruct As IntPtr
Dim gch As GCHandle
Try
'Open the file and read the binary data into a byte array.
fstm = New FileStream(File Name, FileMode.Open,
FileAccess.Read , FileShare.Read)
bFileOpen = True
binaryData = New Byte(fstm.Lengt h - 1) {}
bytesRead = fstm.Read(binar yData, 0, CInt(fstm.Lengt h))
'Initialize/size our array of vertices.
iStructSize = Marshal.SizeOf( GetType(MyStruc t))
ArrayOfStructs =
System.Array.Cr eateInstance(Ge tType(MyStruct) , CInt(fstm.Lengt h /
iStructSize))
'Get a handle to the vert array, pinning it to keep GC from
'zeroing it or moving it around.
gch = GCHandle.Alloc( ArrayOfStructs, GCHandleType.Pi nned)
'Get a pointer to the vert array.
prtMyStruct = gch.AddrOfPinne dObject()
'Use that pointer as a destination to which to copy the
binary data
'from the byte array.
Marshal.Copy(bi naryData, 0, prtMyStruct, bytesRead)
'Free the pinned handle so GC can do it's thing from here
on.
gch.Free()
Catch ex As System.OutOfMem oryException
' An exception could occur if the system is out of
' memory and the block of heap memory could not be
' set aside for you.
Throw ex
Catch e As Exception
' General exception caught, show the message and move on...
Throw e
Finally
If bFileOpen Then
fstm.Close()
End If
fstm = Nothing
If gch.IsAllocated () Then
gch.Free()
End If
End Try
End Sub

Nov 21 '05 #3

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

Similar topics

1
7225
by: Eric Hendriks | last post by:
// In an unmanaged DLL the following function must be called: // int VFGeneralize(const BYTE * const * features); // "features" parameter is supposed to be an array of byte arrays. // function is Marshaled as follows: static extern int VFGeneralize(byte features); In C# I have the following: // Allocate memory to store "Count" references to byte arrays
0
1891
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
2809
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...
6
10813
by: SB | last post by:
I feel dumb to ask because I bet this is a simple question... Looking at the code below, can someone please explain why I get two different values in my Marshal.SizeOf calls (see the commented lines)? TIA! sb
1
4207
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:
10
4984
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
2
7614
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?
2
7198
by: O.B. | last post by:
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.PtrToStructure to copy the all the data into the "other" array? unsafe public struct DeadReckoning {
2
15927
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
8392
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
8305
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8823
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
8730
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...
1
8503
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
8605
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
6163
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...
1
2726
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
1950
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.