3

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.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Ian
  • 4,169
  • 3
  • 37
  • 62
  • @dlev I'm getting this char* from the Scintilla environment so I don't have control over it. I don't get the length directly, but I can calculate it from some other stuff. I just thought that there must be a way to do an equivalent of strlen in C# if they let you handle char*. I know I'm not the first person to think of this. – Ian Apr 11 '12 at 19:48
  • 1
    `char` is two bytes wide, so if your `char*` points to single-byte data, you may not find a null terminator at all. – phoog Apr 11 '12 at 19:49

1 Answers1

5

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.

dlev
  • 48,024
  • 5
  • 125
  • 132
  • +1 good point, but the data has to have some null termination character (its presence is not mandatory). Need to be check if this ok for OP. – Tigran Apr 11 '12 at 19:54
  • 1
    @Tigran the OP's requirement assumes the existence of a null termination character. He presumably understands the risk of bad data causing an access violation. – phoog Apr 11 '12 at 19:55
  • 1
    @Tigran I am assuming a null-terminator is present. If there is a case where it isn't I'll get to know fairly quickly but it apparently always is. – Ian Apr 11 '12 at 20:30