473,569 Members | 2,634 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

efficient way of casting structure and class instances to char*

In C++ we can do things like (Header is an instance of C++ structure)

Send(m_Sock,(ch ar*)&Header,siz eof(Header),0)

in C# we have Socket.Send(byt e[] , int offset, int size, flags)

how do i convert the instance of a C# class or strucute to byte array
efficiently rathen then creating function myself todo that ?

Regards
Nov 16 '05 #1
2 1867
Raza,

If unsafe code is okay okay with you, you can do something like:

byte[] buffer = new byte[sizeof(Header)];

fixed (byte* pBuffer = buffer)
{
Header* pHeader = (Header*) pBuffer;

// set fields of pHeader here.
}

You might also find something useful in the Marshal class.
--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://weblogs.asp.net/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
"raza" <ra**@uraan.com > wrote in message
news:d8******** *************** **@posting.goog le.com...
In C++ we can do things like (Header is an instance of C++ structure)

Send(m_Sock,(ch ar*)&Header,siz eof(Header),0)

in C# we have Socket.Send(byt e[] , int offset, int size, flags)

how do i convert the instance of a C# class or strucute to byte array
efficiently rathen then creating function myself todo that ?

Regards

Nov 16 '05 #2

"raza" <ra**@uraan.com > wrote in message
news:d8******** *************** **@posting.goog le.com...
In C++ we can do things like (Header is an instance of C++ structure)

Send(m_Sock,(ch ar*)&Header,siz eof(Header),0)

in C# we have Socket.Send(byt e[] , int offset, int size, flags)

how do i convert the instance of a C# class or strucute to byte array
efficiently rathen then creating function myself todo that ?

Regards


[StructLayout(La youtKind.Sequen tial)]
public struct Header
{
public int i;
...
...
}

// create header and setup
Header header = new Header();
....

// determine struct size
int size = Marshal.SizeOf( typeof(Header) );

// create byte-array
byte[] buffer = new byte[size];

// pin the byte array
GCHandle hBuffer = GCHandle.Alloc( buffer, GCHandleType.Pi nned );

// marshal struct into the byte array
Marshal.StructT oPtr( header, hBuffer.AddrOfP innedObject(), true );

// free pinning
hBuffer.Free();

// now you can send the buffer
Send( buffer, 0, size, flags );
HTH,
greetings

Nov 16 '05 #3

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

Similar topics

2
6038
by: seia0106 | last post by:
Hello I am writing a function to read a binary file. Here is a part of code #include <fstream> .. .. BYTE *pData; long lDataLen; pms->GetPointer(&pData); lDataLen = pms->GetSize(); // Read one line at a time till end of file..
13
1919
by: Christopher Benson-Manica | last post by:
The thread where casting is being discussed motivated me to try this. Let's say you wanted to populate a BankRecord structure (as I defined below) with 17-character record numbers, but with the record numbers separated into a SSN and an account number (and with a terminating '\0')... #include <stdio.h> #include <stdlib.h> #include...
20
2060
by: j0mbolar | last post by:
I was reading page 720 of unix network programming, volume one, second edition. In this udp_write function he does the following: void udp_write(char *buf, <everything else omitted) struct udpiphdr *ui; struct ip *ip; ip = (struct ip *) buf;
2
2160
by: Enrique Bustamante | last post by:
Casting arrays that works on watch and command window but not in code. My application is casting arrays in a way it should work. To test if I was doing something invalid, I wrote a test code that has similar structure of the classes in my application. The test worked fine, the casting I want to do must work. I compared the structure of the...
3
2751
by: Tigger | last post by:
I have an object which could be compared to a DataTable/List which I am trying to genericify. I've spent about a day so far in refactoring and in the process gone through some hoops and hit some dead ends. I'm posting this to get some feedback on wether I'm going in the right direction, and at the same time hopefully save others from...
8
4256
by: Gamma | last post by:
I'm trying to inherit subclass from System.Diagnostics.Process, but whenever I cast a "Process" object to it's subclass, I encounter an exception "System.InvalidCastException" ("Specified cast is not valid"). How do I fix it ? using System.Diagnostics; .. .. class NewProcess: Process {
3
1890
by: =?Utf-8?B?amFtZXNAbm9zcGFtLmNvbQ==?= | last post by:
I have an existing MFC c++ ocx control that I need to work with a c# class. If I use a locally defined data structure, everything works. For example, in my C++ app I declare. MyCSharpClass DataStructure; To use the data structure in my c# class I use DataAccess::Select(%DataStructure);
2
2626
by: pallav | last post by:
I'm using an old sparse matrix C library in my C++ code and I'd like to know how to downcast a boost::shared_ptr to char *. The sparse matrix data structure is like this: struct sm_element_struct { /* other fields here */ ....... char *user_word; /* user-defined word */ };
6
3003
by: noone | last post by:
What is the syntax to access members of a structure without explicitly naming the structure in every access? struct mytype { int a; char* b; long c; } IT; How can I access the structure members in a way similar to the old pascal
0
7924
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. ...
1
7677
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...
0
7979
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...
1
5514
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...
0
5219
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...
0
3653
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...
1
2115
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
1
1223
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
940
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...

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.