Reputation: 103467
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.
Upvotes: 0
Views: 2707
Reputation: 1063015
A simple approach might be:
for(int i = 0 ; i < reply.Length ; i++) {
buffer[i] = reply[i];
}
buffer[reply.Length] = '\0';
You could also use fixed(char* chars = reply) {...}
and loop over the pointers, but seems overkill.
Upvotes: 3
Reputation: 283694
You could use Marshal.Copy
which is cleaner and likely also faster than the loop.
Upvotes: 5