2

I have the following struct:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct cAuthLogonChallenge
{
    byte cmd;
    byte error;
    fixed byte name[4];

    public cAuthLogonChallenge()
    {
        cmd = 0x04;
        error = 0x00;
        name = ???
    }
}

name is supposed to be a null-terminated ASCII string, and Visual Studio is rejecting all my ideas to interact with it. How do I set it?

2 Answers 2

1

You need to switch to unsafe mode to use fixed statement

http://msdn.microsoft.com/en-us/library/f58wzh21%28v=VS.80%29.aspx

http://msdn.microsoft.com/en-us/library/chfa2zb8%28v=VS.80%29.aspx

http://msdn.microsoft.com/en-us/library/zycewsya%28v=VS.80%29.aspx

Change your struct definition to unsafe struct ... then you can initialize your array like in c/c++

Sign up to request clarification or add additional context in comments.

Comments

1

Got it:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct cAuthLogonChallenge
{
    byte cmd;
    byte error;
    fixed byte name[4];

    public cAuthLogonChallenge(byte dummy)
    {
        cmd = 0x04;
        error = 0x00;
        fixed (byte* p = this.name)
        {
            *p = (byte)'J';
            *(p + 1) = (byte)'o';
            *(p + 2) = (byte)'n';
            *(p + 3) = 0;
        }
    }
}

1 Comment

remember that *[a + b] is identical to a[b] in C#/C++/C ..., meaning that you can write the last 3 lines as p[1] = ...; p[2] = ...; p[3] = ...;

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.