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)
v开发者_开发百科oid 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:
- memset to zero is similar to Array.Clear
- memcpy takes the destination first, whereas Array.Copy takes the source first
- 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);
}
精彩评论