【问题标题】:print string to a byte pointer in c#在c#中将字符串打印到字节指针
【发布时间】:2019-06-08 07:55:16
【问题描述】:

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

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

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

感谢您的帮助。

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

【问题讨论】:

标签: c# c pointers translate


【解决方案1】:

你可以这样做:

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
}              

【讨论】:

  • 您是否试图避开unsafe?对于固定偏移量,您也可以use struct
  • 我没有看到任何与结构相关的内容。是的,如果不需要,我宁愿避免不安全
  • 谢谢,这有助于解决一些错误并理解一些内容。我现在无法测试它,因为我的经理还没有给我任何东西来测试它,但是谢谢你的帮助!
猜你喜欢
  • 2023-03-15
  • 2015-12-26
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 2013-03-09
  • 1970-01-01
  • 2011-09-17
  • 2019-04-09
相关资源
最近更新 更多