473,766 Members | 2,180 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

marshal binary data file, written with C++, with my C# code

I need to read binary data file written by C++ program, using my C#
application.
How do i marshal the bytes i read with my C# code to .NET types.

The data is numbers (integers float doubles etc..) and strings.

I looked at the Marshal class but did not know how to use it with file.
Please add few code lines.

Thanks alot

Jan 19 '06 #1
14 4151
bb
here is something i use for reading a string stored by C++ as an IntPtr
public class MarshalUtil
{
IntPtr m_objData = IntPtr.Zero;
int m_nPosition = 0;

public MarshalUtil(Int Ptr objData)
{
m_objData = objData;
}

public string ReadString()
{
ArrayList objBytes = new ArrayList();
byte byt;
string strData = "";

while((byt = Marshal.ReadByt e(m_objData, m_nPosition)) != 0)
{
strData += (char) byt;
m_nPosition += 2;
}

m_nPosition += 2;

return strData;
}

public bool MoreData
{
get
{
return (Marshal.ReadBy te(m_objData, m_nPosition) != 0);
}
}
}

Jan 19 '06 #2
Thanks bb,

And what about integers float and doubles, how to marshal them ?

:)

Jan 19 '06 #3
bb wrote:
here is something i use for reading a string stored by C++ as an IntPtr

public class MarshalUtil
{
IntPtr m_objData = IntPtr.Zero;
int m_nPosition = 0;

public MarshalUtil(Int Ptr objData)
{
m_objData = objData;
}

public string ReadString()
{
ArrayList objBytes = new ArrayList();
byte byt;
string strData = "";

while((byt = Marshal.ReadByt e(m_objData, m_nPosition)) != 0)
{
strData += (char) byt;
m_nPosition += 2;
}

m_nPosition += 2;

return strData;
}


That will be hideously inefficient with large strings - you should at
the very least be using a StringBuilder. You also seem to be ignoring
every other byte - I don't believe the above will work with strings
containing Unicode characters above U+00FF. Instead, you should read
*two* bytes, and shift one left by 8 bits.

Jon

Jan 19 '06 #4
Vertilka wrote:
And what about integers float and doubles, how to marshal them ?


Have a look at Marshal.ReadInt 32 (etc) for integers. For doubles you
should use Marshal.ReadInt 64 and then call
BitConverter.In t64BitsToDouble . I'm not guaranteeing it will work, but
it's certainly worth a try.

Unfortunately there's no direct equivalent for that process for floats
(at least not in 1.1 - I haven't checked 2.0) - instead you'd probably
want to use BitConverter.To Single(byte[]) having read 4 bytes into a
byte array first.

Jon

Jan 19 '06 #5
You can always use the overload of the static Copy method which takes an
IntPtr and populates an array of doubles (or floats, there is an overload
for that as well). If you want one double/float, you can just declare an
array of one element (a little overkill, I know, but less code, right?).

Also, if the OP is willing to use unsafe code, then it could be much
easier (just cast to the appropriate pointer type and dereference).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:11******** ************@g4 4g2000cwa.googl egroups.com...
Vertilka wrote:
And what about integers float and doubles, how to marshal them ?


Have a look at Marshal.ReadInt 32 (etc) for integers. For doubles you
should use Marshal.ReadInt 64 and then call
BitConverter.In t64BitsToDouble . I'm not guaranteeing it will work, but
it's certainly worth a try.

Unfortunately there's no direct equivalent for that process for floats
(at least not in 1.1 - I haven't checked 2.0) - instead you'd probably
want to use BitConverter.To Single(byte[]) having read 4 bytes into a
byte array first.

Jon

Jan 19 '06 #6
Jon, Nicholas,
Thanks for your answers.

Can you both post code snippets.
Lets say that i have 8 bytes that i want to get a bouble from them.

Thanks.

Jan 19 '06 #7
bb
yes its just used to get a known small length string from my device
driver

although im not sure thats an excuse for hideous code ;-)

Jan 19 '06 #8
Jon,

I tried you advise.
How do i convert array of bytes to IntPtr, to use with
Marshal.ReadInt 32 ?

=== Code snippet ===

FileStream fs = new FileStream(@"C: \myfile.bin", FileMode.Open);

byte[] buffer = new byte[1024];
fs.Read(buffer, 0, 8);

Marshal.ReadInt 64( ???? );

??? BitConverter.In t64BitsToDouble ();

=== Code snippet ===

Jan 19 '06 #9

"Vertilka" <ve******@gmail .com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
| Jon,
|
| I tried you advise.
| How do i convert array of bytes to IntPtr, to use with
| Marshal.ReadInt 32 ?
|
| === Code snippet ===
|
| FileStream fs = new FileStream(@"C: \myfile.bin", FileMode.Open);
|
| byte[] buffer = new byte[1024];
| fs.Read(buffer, 0, 8);
|
| Marshal.ReadInt 64( ???? );
|
| ??? BitConverter.In t64BitsToDouble ();
|
| === Code snippet ===
|

Use the BinaryReader and wrap your FileStream, there is no need to call
Marshal methods, you simply need to call the right read method. Just beware
of the char encoding when reading cjar array's and strings.
string s1;
byte b1;
int i1;
float f1;
double d1;
char[] ca;

....
using(BinaryRea der binReader =
new BinaryReader(Fi le.Open(@".\myf ile.bin", FileMode.Open)) )
{
try {
while (true)
{
s1 = binReader.ReadS tring();
b1 = binReader.ReadB yte();
i1 = binReader.ReadI nt32();
f1 = binReader.ReadS ingle();
d1 = binReader.ReadD ouble();
ca = binReader.ReadC hars(5);
Console.WriteLi ne(f1);
}
}
catch(EndOfStre amException ex)
{
// end of file reached
}
}

Willy.

Jan 19 '06 #10

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

Similar topics

28
2801
by: wwj | last post by:
void main() { char* p="Hello"; printf("%s",p); *p='w'; printf("%s",p); }
4
3695
by: knapak | last post by:
Hello I'm a self instructed amateur attempting to read a huge file from disk... so bear with me please... I just learned that reading a file in binary is faster than text. So I wrote the following code that compiles OK. It runs and shows the requested output. However, after execution, it pops one of those windows to send error reports online to the porgram creator. I have managed to find where the error is but can't see what's wrong....
2
4859
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...
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
21
2577
by: Mike | last post by:
Hi, The example below shows that result of a marshaled data structure is nothing but a string >>> data = {2:'two', 3:'three'} >>> import marshal >>> bytes = marshal.dumps(data) >>> type(bytes) <type 'str'>
2
13128
by: Edvin | last post by:
Why is binary array written to a file different than when converting the binary array to string and then writing it to file! For example: // --- Allocate byte array byte arrByte = new byte; for( int i=1; i< arrByte.Length; i++ ) arrByte = (byte)i;
3
3849
by: masood.iqbal | last post by:
Hi, Kindly excuse my novice question. In all the literature on ifstream that I have seen, nowhere have I read what happens if you try to read a binary file using the ">>" operator. I ran into the two problems while trying to read a binary file. 1). All whitespace characters were skipped 2). Certain binary files gave a core dump
13
3713
by: swetha | last post by:
HI Every1, I have a problem in reading a binary file. Actually i want a C program which reads in the data from a file which is in binary format and i want to update values in it. The file consists of structures of type---- struct record { int acountnum; char name; float value;
10
22743
by: rory | last post by:
I can't seem to append a string to the end of a binary file. I'm using the following code: fstream outFile("test.exe", ios::in | ios::out | ios::binary | ios::ate | ios::app) outFile.write("teststring", 10); outFile.close(); If I leave out the ios::ate and ios::app modes my string is written to the start of the file as I'd expect but I want to write the data to
0
9571
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
9404
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
10168
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
9959
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
9838
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
6651
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5279
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2806
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.