将字符串打印到 C# 中的字节指针

print string to a byte pointer in c#

我正在尝试将 C 代码翻译成 C#,但我偶然发现了一行代码,我在翻译时遇到了问题。

sprintf((char*)&u8FirmareBuffer[0x1C0] + strlen((char*)&u8FirmareBuffer[0x1C0]), ".B%s", argv[3]);

特别是这一行。 u8FirmwareBuffer 是 C 中的无符号字符数组,我猜是 C# 中的字节数组。 argv[3] 是一个字符串。 如何将此行翻译成 C#。

感谢您的帮助。

编辑:这已被标记为重复,但我认为它们有所不同,因为我使用的指针不适用于标记 post 上提供的解决方案。

你可以这样做:

string myString = "This is my string";
byte[] buffer = new byte[1024];
int offset = 0;

    // if you pass a byte buffer to the constructor of a memorystream, it will use that, don't forget that it cannot grow the buffer.
using (var memStream = new MemoryStream(buffer))
{
    // you can even seek to a specific position
    memStream.Seek(offset, SeekOrigin.Begin);

    // check your encoding..
    var data = Encoding.UTF8.GetBytes(myString);

    // write it on the current offset in the memory stream
    memStream.Write(data, 0, data.Length);
}

也可以使用 StreamWriter

string myString = "This is my string";
byte[] buffer = new byte[1024];
int offset = 0;

// if you pass a byte buffer to the constructor.....(see above)
using (var memStream = new MemoryStream(buffer))
using (var streamWriter = new StreamWriter(memStream))
{
    // you can even seek to a specific position
    memStream.Seek(offset, SeekOrigin.Begin);

    streamWriter.Write(myString);
    streamWriter.Flush();

    // don't forget to flush before you seek again
}