Cast a byte array to a structure

G

Guest

Hello,

I need to interact with the Win32 API "BackupRead," and it returns a byte
array as one of its parameters.

I need to be able to cast the first part of the byte array into a special
structure that describes the data contained in the rest of the byte array.

How can I do this? For example:

byte [] A = new byte[100];

struct SpecialStruct
{
int a;
string b;
};

// I want to be able to perform a cast-like operation such as this:

SpecialStruct S = (SpecialStruct) A; // Remember, A is the byte array

How can I accomplish something like this in C#??

Thank you very much,
Rich
 
G

Guest

I need to interact with the Win32 API "BackupRead," and it returns a byte
array as one of its parameters.

Only if you declare it that way. You can also make the second parameter an
IntPtr and pass in a pointer to a native memory buffer. Then you can use
Marshal.PtrToStructure to retrieve the header struct.

I need to be able to cast the first part of the byte array into a special
structure that describes the data contained in the rest of the byte array.

How can I do this? For example:

byte [] A = new byte[100];

struct SpecialStruct
{
int a;
string b;
};

// I want to be able to perform a cast-like operation such as this:

SpecialStruct S = (SpecialStruct) A; // Remember, A is the byte array

How can I accomplish something like this in C#??

Well for trivial structures like these you can do something like

SpecialStruct S;
S.a = BitConverter.ToInt32(A, 0);
S.b = Encoding.Unicode.GetString(A, 4, length); // replace Unicode with
appropriate encoding


Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top