I need to copy a C# string into a char*. I have this code, which works, but looks clumsy. Is there a more elegant way to do this?
public unsafe static void GetReply(char* buffer) {
string reply = "Hello, world"; // or whatever
// clumsy code:
var i = buffer;
foreach (char x in reply.ToCharArray()) {
*i = x;
i++;
}
*i = '\0';
}
Note: buffer is guaranteed to point to allocated memory of known length. No problems there.
You could use
Marshal.Copywhich is cleaner and likely also faster than the loop.