1

Ok this one might be simple but I don't have any experience with dealing unmanaged memory within C#. I got a structure in my project containing a fixed length array of four bytes:

[StructLayout(LayoutKind.Sequential)]
unsafe struct MessageHeader {
    ...
    public fixed byte Prefix[4];
    ...
}

Now all I want to do is creating an object of type MessageHeader and assign some bytes to the prefix. I tried the following:

MessageHeader x;
unsafe {
    fixed (byte* ptr = x.Prefix) {
        Marshal.Copy(new byte[] { 128 , 64, 128, 64 }, 0, new IntPtr(ptr), 4); 
    }
    ...
}

However I got the following error: "You cannot use a fixed statement to take the address of an already fixed expression".

I tried to use it without fixed:

Marshal.Copy(new byte[] { 128, 64, 128, 64 }, 0, new IntPtr(x.Prefix), 4);

But this gives me the error of a possibly uninitialized struct. Shouldn't that be irrelevant on writing to an arbitrary unmanaged buffer?

1 Answer 1

1

Try this one. The x.Prefix is already pointer and it is already fixed.

MessageHeader x;

// other ways to initialize x:
// var x = default(MessageHeader);
// var x = new MessageHeader();

unsafe
{
    Marshal.Copy(new byte[] { 128, 64, 128, 64 }, 0, new IntPtr(x.Prefix), 4);
}
Sign up to request clarification or add additional context in comments.

7 Comments

Don't see a difference between your code line and my second code line... As I already stated, I get an error about the uninitialized struct
You actually write your x initialization as var x = new MessageHeader();
Oh my bad, it has been an old error message, on rebuild it works. Sorry for that. Anyway I still get the same error message down below the Marshal.Copy (Use of unassigned variable 'x') when I try to pass the struct somewhere into a method. Any ideas?
"So new MessageHeader() is needed? Can't it be allocated on stack?" It will be on stack anyway. It is equal to var x = default(MessageHeader);
Ok, I initialized the struct as shown in your last posting, now everything works fine. Thank you very much for your help :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.