none
Get C# string from an LPCSTR RRS feed

  • Question

  • Within an unsafe context, I have an LPCSTR pointer. How do I create a C# string from that? I could scan the pointed to memory one character at a time until a null character is reached. But, there must be a better way? Thanks.
    Tuesday, August 21, 2018 1:07 AM

Answers

  • The String class has constructors that take a pointer to signed bytes (sbyte*). Therefore, you can use one with LPCSTR, if the array is null-terminated, or you know the length and encoding. Show some details about your code.


    • Edited by Viorel_MVP Tuesday, August 21, 2018 4:48 AM
    • Marked as answer by Dev10110110 Tuesday, August 21, 2018 9:19 AM
    Tuesday, August 21, 2018 4:41 AM

All replies

  • Cast your pointer to IntPtr (I assume you have done that) then use Marshal.PtrToStringAuto() or it's more specific version like .PtrToStringUnicode() to convert it (I assume the remote side have _UNICODE preprocessor directive defined).

    (For some reason I can't link the page to the keyword here, so I'll just paste it below)

    https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.ptrtostringauto?view=netframework-4.7.2


    Tuesday, August 21, 2018 1:27 AM
    Answerer
  • The String class has constructors that take a pointer to signed bytes (sbyte*). Therefore, you can use one with LPCSTR, if the array is null-terminated, or you know the length and encoding. Show some details about your code.


    • Edited by Viorel_MVP Tuesday, August 21, 2018 4:48 AM
    • Marked as answer by Dev10110110 Tuesday, August 21, 2018 9:19 AM
    Tuesday, August 21, 2018 4:41 AM
  • Thank you to both. I will take the shorter solution as the answer, although both are probably good. I am playing with strings inside the PE file. I have no knowledge of the PE implementation details. But the following does work and returns a string such as "KERNEL32.dll".

    new string ( (sbyte *) pInstantiatedImage + pInstantiatedImageBaseImportDescriptor->Name )




    • Edited by Dev10110110 Tuesday, August 21, 2018 9:29 AM
    Tuesday, August 21, 2018 9:19 AM