Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling char* in C# (strlen function?)

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.

like image 408
Ian Avatar asked Aug 26 '26 00:08

Ian


1 Answers

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.

like image 66
dlev Avatar answered Aug 27 '26 13:08

dlev