convert from managed String to unmanaged char

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
 
W

William DePalo [MVP VC++]

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
 
G

Guest

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
 
W

William DePalo [MVP VC++]

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top