Question

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,

Was it helpful?

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

OTHER TIPS

I would prefer not creating a copy

You have to create a copy, System::String is structurally very different from const char*. The Marshal class has a simple helper method that makes this conversion, you can specify how many bytes to convert to you don't need a properly terminated C-string. An example program:

#include "stdafx.h"

using namespace System;
using namespace System::Diagnostics;
using namespace System::Runtime::InteropServices;

int main(array<System::String ^> ^args)
{
    const char* str = "yada12345garbage...";
    String^ s = Marshal::PtrToStringAnsi(IntPtr((void*)&str[4]), 5);
    Debug::Assert(s == "12345");
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top