0

I've been trying to get rid of the unmanaged code that I'm currently using on my source code after a friend suggested why I shouldn't be using unmanaged code. However I seem to keep facing a couple of issues here and there. For most case scenarios I used Buffer.BlockCopy() as it seemed to be the most adequate method but there are still a few in which I'm not sure what to use.

Basically this is used to handle packets that are sent between a server and a client. WriteInt16 is a function used to write ushortvalues in the byte array for example. (1. is basically just doing this at offset 20 and 22).

I'll leave a couple examples below:

1.

fixed (byte* p = Data)
{
    *((ushort*)(p + 20)) = X;//x is an ushort
    *((ushort*)(p + 22)) = Y;//y is an ushort
}

2.

private byte* Ptr
    {
        get
        {
            fixed (byte* p = PData)
                return p;
        }
    }

3.

public unsafe void WriteInt16(ushort val)
    {
        try
        {
            *((ushort*)(Ptr + Count)) = val;
            Count += 2;
        }
        catch{}
    }
8
  • 1
    Why don't you use a strong type for whatever this data represents? Side note: I like how it took your friend telling you it was unsafe rather than just realizing that from the keyword unsafe that you have to use. Commented Dec 27, 2016 at 23:11
  • I knew it was unsafe by the keyword, what I meant is that he explained me why I shouldn't be using unsafe code and its implications Commented Dec 27, 2016 at 23:18
  • 1
    What is the code supposed to do? It's hard to suggest alternatives when it's not clear what the purpose is. Commented Dec 27, 2016 at 23:22
  • Also an empty catch{} is bad practice whether or not the code is unsafe. Commented Dec 27, 2016 at 23:23
  • 1
    Also note that C# code is never "unmanaged". It can be "unsafe" but is is always still "managed" code. Commented Dec 27, 2016 at 23:31

1 Answer 1

0

Assuming little Endian platform and byte arrays (not tested):

*((ushort*)(p + 20)) = X;

is

Data[20] = (byte)X;
Data[21] = (byte)(X >> 8);

and

*((ushort*)(Ptr + Count)) = val;

is

PData[Count] = (byte)val;
PData[Count + 1] = (byte)(val >> 8);
Sign up to request clarification or add additional context in comments.

Comments

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.