簡體   English   中英

如何將此方法從 C++ 轉換為 C#?

[英]How can I convert this method from C++ 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);
}

你的問題的確切答案是這樣的。 這是 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++ 到 C# 遷移指針:

  1. memset 為零類似於 Array.Clear
  2. memcpy 先取目標,而 Array.Copy 先取源
  3. string.Length 是一個屬性,而不是 std::string.length() 中的方法

查看 Buffer.BlockCopy

msdn鏈接

ASCIIEncoding.GetBytes在腦海。 它將您的字符串作為參數並返回包含您的字符串的byte[]緩沖區。

您是否嘗試將二進制數據寫入 stream、文件或類似文件? 如果是這樣,您可能最好使用BinaryWriter ,因為它本身支持序列化字符串(以及其他類型,就此而言)。

使用類似這樣的東西將字符串轉換為字節數組,然后使用 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