I'm dealing with a char* in C# code (in an unsafe section). Is there any way to call the strlen function from C#. It goes against all common sense to have to write a custom strlen function to search for the null terminator. Isn't there a way to call strlen from C# or a similar method that I have access to?
In the big picture I'm trying to convert the char* to a string object, but the characters are in ANSCII format, so I'm going to use the .NET Encoding.Convert namespace to convert it. But I need to know the length of the string before I do that.
Marshal.PtrToStringAnsi() does exactly what you need:
Allocates a managed String and copies all characters up to the first null character from a string stored in unmanaged memory into it.
Incidentally, the method calls lstrlenA on the pointer, which is actually just an import from kernel32.dll. In other words, there does not appear to be a managed "get me the length of this unmanaged string" method available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With