473,804 Members | 3,019 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

reading binary file to struct

I am trying to read a binary file into a struct, but am having trouble
getting all the data.

the struct and a snip of the code follows at the end of the message.
Expected results: 'Sai,,LW,'
Actual results: 'i,,L,'

It appears that only the last letter of the sTmCode is assigned in the
struct.
It appears that only the first letter of the sPos is assisgned in the
struct.

I am sure I am missing something little, but can't see it. any ideas?

Thanks
Derrick

Struct:
[StructLayout(La youtKind.Sequen tial)]
struct PlayerIndexRec
{
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 3)] public string sTmCode;
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 2)] public string sNull1;
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 2)] public string sPos;
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 3)] public string sNull2;
}

Code:
PlayerIndexRec pir = new PlayerIndexRec( );
buf = br.ReadBytes(Ma rshal.SizeOf(pi r));
IntPtr buffer = Marshal.AllocHG lobal( Marshal.SizeOf( pir.GetType() ));
Marshal.Copy( buf, 0, buffer, Marshal.SizeOf( pir) );
pir = (PlayerIndexRec )Marshal.PtrToS tructure(buffer , pir.GetType() );
Marshal.FreeHGl obal( buffer );
Console.WriteLi ne("{0},{1},{2} ,{3}",
pir.sTmCode,
pir.sNull1,
pir.sPos,
pir.sNull2);

Nov 16 '05 #1
5 7066
Hi Derrick,

First of all, I would like to confirm my understanding of your issue. From
your description, I understand that your deserialization code could not
deserialize a struct properly. If there is any misunderstandin g, please
feel free to let me know.

I think there might be something wrong with the size you have allocated for
the struct. You only allocated 3 chars for the first string member.
However, "Sai" actually consists of 4 chars. The system will add a '\0' at
the end of it automatically to indicate that the string is ended. So Would
you try to increase the SizeConst for each member?

[StructLayout(La youtKind.Sequen tial)]
struct PlayerIndexRec
{
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 4)] public string sTmCode;
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 2)] public string sNull1;
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 2)] public string sPos;
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 3)] public string sNull2;
}

HTH.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Nov 16 '05 #2
Thanks for the reply

I tried that prior to posting ie.
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 3)] public string sTmCode;
changed to this
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 4)] public string sTmCode;

The problem with that is that the struct is a different size than the data
in the file - so when I read the data, it goes out of alignment.

I have been able to read the file using VB6.0 with the following Type:
Type PlayerIndexRec
sTmCode As String * 3
sNull1 As String * 2
sPos As String * 2
sNull2 As String * 3
End Type

I found this text in help 'The behavior in managed code differs from the
Microsoft Visual Basic 6.0 behavior, which is not null terminated (for
example, MyString As String * 5).' Could I be using the wrong
UnmanagedType?

Derrick
"Kevin Yu [MSFT]" <v-****@online.mic rosoft.com> wrote in message
news:Aq******** ******@cpmsftng xa10.phx.gbl...
Hi Derrick,

First of all, I would like to confirm my understanding of your issue. From
your description, I understand that your deserialization code could not
deserialize a struct properly. If there is any misunderstandin g, please
feel free to let me know.

I think there might be something wrong with the size you have allocated
for
the struct. You only allocated 3 chars for the first string member.
However, "Sai" actually consists of 4 chars. The system will add a '\0' at
the end of it automatically to indicate that the string is ended. So Would
you try to increase the SizeConst for each member?

[StructLayout(La youtKind.Sequen tial)]
struct PlayerIndexRec
{
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 4)] public string sTmCode;
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 2)] public string sNull1;
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 2)] public string sPos;
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 3)] public string sNull2;
}

HTH.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Nov 16 '05 #3
Hi Derrick,

Since Strings in VB6 are fixed length, when converting to .NET apps, we
have to add VBFixedString(l ength) in the attribute. Please try to use the
following in VB.NET and deserialize it agiain. I haven't found an
equivalance in C#.

Structure PlayerIndexRec

<VBFixedString( 3),System.Runti me.InteropServi ces.MarshalAs(S ystem.Runtime.I n
teropServices.U nmanagedType.By ValTStr,SizeCon st:=3)> Public sTmCode As
String

<VBFixedString( 2),System.Runti me.InteropServi ces.MarshalAs(S ystem.Runtime.I n
teropServices.U nmanagedType.By ValTStr,SizeCon st:=2)> Public sNull1 As String

<VBFixedString( 2),System.Runti me.InteropServi ces.MarshalAs(S ystem.Runtime.I n
teropServices.U nmanagedType.By ValTStr,SizeCon st:=2)> Public sPos As String

<VBFixedString( 3),System.Runti me.InteropServi ces.MarshalAs(S ystem.Runtime.I n
teropServices.U nmanagedType.By ValTStr,SizeCon st:=3)> Public sNull2 As String
End Structure

HTH.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Nov 16 '05 #4
Thanks for the tip.

I converted the code to VB and tested, but am still getting the same
problem.

Following is code snippets - hopefully you can see something I am doing
wrong...
<struct>
Structure PlayerIndexRec
<VBFixedString( 3),
MarshalAs(Syste m.Runtime.Inter opServices.Unma nagedType.ByVal TStr,
SizeConst:=3)> Public sTmCode As String
<VBFixedString( 2),
MarshalAs(Syste m.Runtime.Inter opServices.Unma nagedType.ByVal TStr,
SizeConst:=2)> Public sNull1 As String
<VBFixedString( 2),
MarshalAs(Syste m.Runtime.Inter opServices.Unma nagedType.ByVal TStr,
SizeConst:=2)> Public sPos As String
<VBFixedString( 3),
MarshalAs(Syste m.Runtime.Inter opServices.Unma nagedType.ByVal TStr,
SizeConst:=3)> Public sNull2 As String
End Structure

<Deserialize function>
Private Function RawDeserialize( ByVal rawdatas As Byte(), ByVal anytype As
Type) As Object
Dim rawsize As Integer = Marshal.SizeOf( anytype)
If rawsize > rawdatas.Length Then
Return Nothing
End If
Dim buffer As IntPtr = Marshal.AllocHG lobal(rawsize)
Marshal.Copy(ra wdatas, 0, buffer, rawsize)
Dim retobj As Object = Marshal.PtrToSt ructure(buffer, anytype)
Marshal.FreeHGl obal(buffer)
Return retobj
End Function

<code to read data to struct>
With br
Do While .PeekChar <> -1
Dim pir As New PlayerIndexRec
buf = br.ReadBytes(Ma rshal.SizeOf(pi r))
pir = CType(RawDeseri alize(buf, pir.GetType()), PlayerIndexRec)
Console.WriteLi ne("tmCode: '{0}', sNull1: '{2}', sPos: '{1}', sNull2:
'{3}'", _
pir.sTmCode, _
pir.sPos, _
pir.sNull1, _
pir.sNull2)
Loop
br.Close()
End With

"Kevin Yu [MSFT]" <v-****@online.mic rosoft.com> wrote in message
news:f9******** *****@cpmsftngx a10.phx.gbl...
Hi Derrick,

Since Strings in VB6 are fixed length, when converting to .NET apps, we
have to add VBFixedString(l ength) in the attribute. Please try to use the
following in VB.NET and deserialize it agiain. I haven't found an
equivalance in C#.

Structure PlayerIndexRec

<VBFixedString( 3),System.Runti me.InteropServi ces.MarshalAs(S ystem.Runtime.I n
teropServices.U nmanagedType.By ValTStr,SizeCon st:=3)> Public sTmCode As
String

<VBFixedString( 2),System.Runti me.InteropServi ces.MarshalAs(S ystem.Runtime.I n
teropServices.U nmanagedType.By ValTStr,SizeCon st:=2)> Public sNull1 As
String

<VBFixedString( 2),System.Runti me.InteropServi ces.MarshalAs(S ystem.Runtime.I n
teropServices.U nmanagedType.By ValTStr,SizeCon st:=2)> Public sPos As String

<VBFixedString( 3),System.Runti me.InteropServi ces.MarshalAs(S ystem.Runtime.I n
teropServices.U nmanagedType.By ValTStr,SizeCon st:=3)> Public sNull2 As
String
End Structure

HTH.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Nov 16 '05 #5
Hi Derrick,

Could you also show me the code in VB6 that serializes the object?

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Nov 16 '05 #6

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

Similar topics

0
356
by: Derrick | last post by:
I am trying to read a binary file into a struct, but am having trouble getting all the data. the struct and a snip of the code follows at the end of the message. Expected results: 'Sai,,LW,' Actual results: 'i,,L,' It appears that only the last letter of the sTmCode is assigned in the struct. It appears that only the first letter of the sPos is assisgned in the
3
2627
by: poifull | last post by:
Hi All, What is the proper way to read a binary file into a byte? I am using BinaryReader to read from a Stream and call the ReadByte method of the BinaryReader object. The method I'm using leads to the second question. I got the "Conversion buffer overflow" error when I run the following code: Stream s = openFileDialog1.OpenFile();
6
1624
by: al jones | last post by:
I picked a good project to try to learn to use VS - and up till now everything has worked the way I expect. The code is from a VS.net class, which I picked up on the web, from which I've extracted portions to fulfill my immediate needs. I hsve the following: Structure OFFSETTABLE ' (page 32: "The Table Directory") Friend Version As Long ' signed floating point number ' 2.14 (0x00010000 for TTF version 1.0) Friend...
1
1511
by: RML | last post by:
Hi, My VS 2005 VB app reads a binary file that was created by a VS 2005 VC++ WinCE app. The VC++ app writes the following structure to the file. typedef struct { short ID; TCHAR Num; } PARTS_STRUCT;
8
2717
by: Shalaka Joshi | last post by:
Hi, I have binary file say, "test.bin". I write "FF" in the file and expect my code to read 255 for me. char * lbuf; int lreadBytes ; long lData; FILE *pFile = fopen ("c:\\testbin","rb");
3
1495
by: acp26b | last post by:
I need to read a binary to put into a struct. For some reason the code will not work. In this section of code i am just looping through the file to get the number of records so i can then build the correct size array. Nothing was happening so i used the variable test and found out that read is returning -1. Any ideas? char *inFileName = NULL; void *input; int fdi; int sizeOfData = sizeof(bin_record);
9
9888
by: Use*n*x | last post by:
Hello, I have a binary file (image file) and am reading 4-bytes at a time. The File size is 63,480,320 bytes. My assumption is that if I loop through this file reading 4 bytes at a time, I should loop 15,870,080 times. The code is: newprogram.cpp =============
11
3601
by: Freddy Coal | last post by:
Hi, I'm trying to read a binary file of 2411 Bytes, I would like load all the file in a String. I make this function for make that: '-------------------------- Public Shared Function Read_bin(ByVal ruta As String) Dim cadena As String = "" Dim dato As Array If File.Exists(ruta) = True Then
4
3375
by: Giacomo | last post by:
Hello.. i'm using php on linux --version: PHP 5.2.5 (cli) (built: Apr 25 2008 18:40:41) Copyright (c) 1997-2007 The PHP Group Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies and i'm experiencing unexpected behavior using fread with a binary file. Look at this code: i have a jpeg image of 2290 bytes long, but fread cannot read it correctly, like fgetc does:
1
1694
by: ziopulcher | last post by:
Good morning. I need some help in order to load a binary file. I know that the first 3200 bytes of this file are a "text" header (40 rows x 80 columns). I tried to read them by using the "get" instruction, but I don't know how to convert in the ascii text i have just numbers. May somebody help me? Thank you very much
0
9705
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
9575
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
10073
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
9134
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...
1
7609
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
5645
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4288
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
3806
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2981
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.