Search code examples
c++marshallingmanaged-c++

Managed C++ how to convert NOT Null terminated const char * to String ^


In my Native + Managed code project, I need to convert a const char * (Not null terminated) to Managed String ^. Following code works well when the char * is properly null terminated. However it returns crazy strings when the char * is not null terminated.

String^ STAK::CLRServerProxy::ToCLR(const char* str)
{
    return msclr::interop::marshal_as<String^>(str);    
}

Is there a way I can ask it to marshal this native char * to only first 5 characters ? (This native string is always 5 chars long)

Thank you,


Solution

  • String^ STAK::CLRServerProxy::ToCLR(const char* str)
    {
        return Marshal::PtrToStringAnsi((IntPtr) (char *) str, 5)
    }
    

    or if you want to make it more flexible

    String^ STAK::CLRServerProxy::ToCLR(const char* str, size_t n)
    {
        return Marshal::PtrToStringAnsi((IntPtr) (char *) str, n)
    }
    

    Calling by passing 5 as the 2nd param