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

时间:2011-06-14 16:41:58

标签: c# 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);
}

5 个答案:

答案 0 :(得分:4)

你的问题的确切答案是这样的。这是C#类中的私有方法(为了清楚起见,我还添加了缓冲区字节数组):

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

  1. memset为零与Array.Clear
  2. 类似
  3. memcpy首先获取目标,而Array.Copy首先获取源
  4. string.Length是一个属性,而不是std :: string.length()
  5. 中的方法

答案 1 :(得分:3)

查看Buffer.BlockCopy

msdn link

答案 2 :(得分:2)

想到了{p> ASCIIEncoding.GetBytes。它将您的字符串作为参数并返回包含您的字符串的byte[]缓冲区。

答案 3 :(得分:1)

您是否尝试将二进制数据写入流,文件或类似内容?如果是这样,你可能最好使用BinaryWriter,因为它原生支持序列化字符串(以及其他类型)。

答案 4 :(得分:1)

使用类似的东西将字符串转换为字节数组,然后使用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);
}