简体   繁体   中英

How can I convert this method from C++ to C#?

Could someone explain how I'd write this to C#?

//byte[] buffer is priavte in the class
//it's for writing Packets (gameserver)
void writeString(int location, std::string value, int length) {
    if (value.length() < length) {
        memcpy(&buffer[location], value.c_str(), value.length());
        memset(&buffer[location+value.length()], 0, length-value.length());
    }
    else memcpy(&buffer[location], value.c_str(), length);
}

The exact answer to your question is this. This is a private method within a C# class (I also added the buffer byte array for clarity):

    byte[] buffer;
    private void writeString(int location, string value, int length)
    {
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

        if (value.Length < length)
        {
            Array.Copy(encoding.GetBytes(value), 0, buffer, location, value.Length);
            Array.Clear(buffer, location, length - value.Length);
        }
        else Array.Copy(encoding.GetBytes(value), 0, buffer, location, length);
    }

C++ to C# migration pointers:

  1. memset to zero is similar to Array.Clear
  2. memcpy takes the destination first, whereas Array.Copy takes the source first
  3. string.Length is a property, not a method as in std::string.length()

Check out Buffer.BlockCopy

msdn link

ASCIIEncoding.GetBytes comes to mind. It takes your string as a parameter and returns a byte[] buffer containing your string.

Are you trying to write binary data to a stream, file or similar? If so, you're probably better off using a BinaryWriter , as it natively supports serializing strings (and other types, too, for that matter).

Use something like this to convert the string to a byte array, then use a for loop to put those bytes into the byte array that is your message buffer and to zero-fill if necessary

// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
    System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
    return encoding.GetBytes(str);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM