convert from managed String to unmanaged char

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

In managed C++, there is variable String *s. The variable got value from a
C# assembly. Then I need to convert it into char *c in order to call
an external function in a dll that accepts parameter func(char c[]).

How to convert from String *s to char *c?

thanks

Keith
 
keith said:
In managed C++, there is variable String *s. The variable got value from a
C# assembly. Then I need to convert it into char *c in order to call
an external function in a dll that accepts parameter func(char c[]).

How to convert from String *s to char *c?

This gets you a pointer to the (wide) characters that comprise the string:

#include <vcclr.h>

wchar_t __pin *pStr = PtrToStringChars(s);

At that point you'll need to convert to ANSI. Check the docs for conversion
functions such as wcstombs() or WideCharToMultiByte().

Regards,
Will
 
using namespace System::Runtime::InteropServices;
const char* FileStr = (const char*)(Marshal::StringToHGlobalAnsi(in_file)).ToPointer();
// Do what you want with FileStr
Marshal::FreeHGlobal(IntPtr((void*)FileStr));

That is what I did, and it seemed to work fine
 
Rambuncle said:
using namespace System::Runtime::InteropServices;
const char* FileStr = (const char*)(Marshal::StringToHGlobalAnsi(in_file)).ToPointer();
// Do what you want with FileStr
Marshal::FreeHGlobal(IntPtr((void*)FileStr));

That is what I did, and it seemed to work fine

Yup, it does. Just make sure to free the memory when you are done.

Regards,
Will
 
Back
Top