Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how I can convert a structure to a byte array with c # and how I can make the function reciproce another project in c + + but without losing data
Posted
Updated 12-Feb-13 4:51am
v3

There is no standard method of doing this, as it depends on what types you have in your struct, and what restrictions you have.

For instance, if you're not concerned with optimal speed and space, you could stream the struct to/from XML (this is relatively trivial in C#, but more complicated in C++) and send the XML string as a byte array.

Keep in mind that even simple types are not necessarily the same size in C# and C++, and floating point numbers in particular will have different memory layout. That's why they are often transferred as text, or broken up into exponent and mantissa.
 
Share this answer
 
Comments
AbassiOmar 12-Feb-13 11:17am    
Here is my structure
struct A
{
int a;
int b;
byte [] T;
}
I want this vonvertir structure byte [] and I need to recover the other party in c + + and I have to convert this byte [] in this struct
>> how I can convert a structure to a byte tbleau array
struct A
{ int i; };


A a;

char* ptr_to_array = (char*)&a;

You don't need to convert the structure, it is after all just an array of bytes already ...

As for roundtripping through .Net (c#) - you should perhaps use System.IntPtr[^], or perhaps something else - as it's not entirely clear what you want.

Best regards
Espen Harlinn
 
Share this answer
 
Comments
AbassiOmar 12-Feb-13 10:56am    
no I want to convert struct to byte [] in C # and convert byte [] to struct in c + +
it is the same data sent from c # to c + +
Espen Harlinn 12-Feb-13 11:04am    
Here goes: http://msdn.microsoft.com/en-us/library/bd99e6zt.aspx
In C#, int is a signed 32-bit value, which gives a 4-byte array, so you could just write those bytes to the array like this:

C#
void IntToArray(int val, byte[] array, int index)
{
    // Convert int to uint to make bit handling tidier
    uint temp = unchecked((uint)val);
    for (int i = 0; i < 4; ++i)
    {
        array[index + i] = (byte)((temp >> i*8) & 0xff);
    }
}

byte[] StructAToArray(A a)
{
    byte[] array = new byte[8 + a.T.Length];
    // First int
    IntToArray(a.a, array, 0);
    // Second int, 4 bytes later
    IntToArray(a.b, array, 4);
    // Array, 4 bytes later again
    Array.Copy(a.T, 0, array, 8, a.T.Length);
    // Done
    return array;
}

Then you just have to do the corresponding conversion on the C++ side. :-)
 
Share this answer
 
Comments
AbassiOmar 12-Feb-13 12:11pm    
thanks what i need

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900