Search code examples
c#cpointerstranslate

print string to a byte pointer in c#


I'm tring to translate C code to C# and I stumbled upon a line of code which I'm having problems translating.

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

specifically this line. u8FirmwareBuffer is a unsigned char array in C, a byte array in C# I would guess. argv[3] is a string. How can I translate this line to C#.

Thank you for your help.

Edit: This has been marked as a duplicate, but I think they differenciate because I am using pointers which don't work with the solutions presented on the marked post.


Solution

  • You could do something like:

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

    It's also possible with a 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
    }