简体   繁体   English

如何将此方法从 C++ 转换为 C#?

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

Could someone explain how I'd write this to C#?有人可以解释我如何将其写入 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):这是 C# class 中的私有方法(为清楚起见,我还添加了缓冲区字节数组):

    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: C++ 到 C# 迁移指针:

  1. memset to zero is similar to Array.Clear memset 为零类似于 Array.Clear
  2. memcpy takes the destination first, whereas Array.Copy takes the source first memcpy 先取目标,而 Array.Copy 先取源
  3. string.Length is a property, not a method as in std::string.length() string.Length 是一个属性,而不是 std::string.length() 中的方法

Check out Buffer.BlockCopy查看 Buffer.BlockCopy

msdn link msdn链接

ASCIIEncoding.GetBytes comes to mind. ASCIIEncoding.GetBytes在脑海。 It takes your string as a parameter and returns a byte[] buffer containing your string.它将您的字符串作为参数并返回包含您的字符串的byte[]缓冲区。

Are you trying to write binary data to a stream, file or similar?您是否尝试将二进制数据写入 stream、文件或类似文件? If so, you're probably better off using a BinaryWriter , as it natively supports serializing strings (and other types, too, for that matter).如果是这样,您可能最好使用BinaryWriter ,因为它本身支持序列化字符串(以及其他类型,就此而言)。

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使用类似这样的东西将字符串转换为字节数组,然后使用 for 循环将这些字节放入作为消息缓冲区的字节数组中,并在必要时进行零填充

// 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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