Conversion

H

hipek

Hi, all,

I don't know how to convert Char* to System::String* in Visual C++ 2005,
I found something about conversion form other side (String* to Char*) but
nothing about that.

I need to put some text form Char* into textBox and I don't know how to do
that.
Thank for your hints.

Hipek.
 
J

Jochen Kalmbach [MVP]

Hi hipek!
I don't know how to convert Char* to System::String* in Visual C++ 2005,

What ist "Char*" ?
And waht ist "String*" ?

I only know "String^"...

Do you mean "char* szVal"?

Try

String ^str = gcnew String(szVal);

--
Greetings
Jochen

My blog about Win32 and .NET
http://blog.kalmbachnet.de/
 
H

hipek

Yes I mean String^. I'm using some C API in my project and some API
functions operate on char*. I have to convert char* to String^ and sometimes
in other side in order tu put it into some visual components as properties.
Before I've never used Visual Studio C++ and cli/C++ for my projects and I
need to learn more about it.

Thanks for your hint, you've been most helpfull.

Hipek.
 
J

Jochen Kalmbach [MVP]

Hi hipek!
Yes I mean String^. I'm using some C API in my project and some API
functions operate on char*. I have to convert char* to String^ and sometimes
in other side in order tu put it into some visual components as properties.
Before I've never used Visual Studio C++ and cli/C++ for my projects and I
need to learn more about it.

For converting String^ to char or wchar_t I suggest the following, which
handles everything for you (also if someone throws an exception):

#include <windows.h>
#include <tchar.h>
#include <string>
using namespace System;
struct StringConvA
{
char *szAnsi;
StringConvA(System::String ^s)
:
szAnsi(static_cast<char*>(System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(s).ToPointer()))

{}
~StringConvA()
{

System::Runtime::InteropServices::Marshal::FreeHGlobal(IntPtr(szAnsi));
}
operator LPCSTR() const
{
return szAnsi;
}
};

struct StringConvW
{
wchar_t *szUnicode;
StringConvW(System::String^ s)
:
szUnicode(static_cast<wchar_t*>(System::Runtime::InteropServices::Marshal::StringToHGlobalUni(s).ToPointer()))

{}
~StringConvW()
{

System::Runtime::InteropServices::Marshal::FreeHGlobal(IntPtr(szUnicode));
}
operator LPCWSTR() const
{
return szUnicode;
}
};

#ifdef _UNICODE
#define StringConvT StringConvW
#else
#define StringConvT StringConvA
#endif

int _tmain()
{
String ^s = "abc";
std::string ansi = StringConvA(s);
std::wstring unicode = StringConvW(s);
_tprintf(_T("%s"), (LPCTSTR) StringConvT(s));
}

--
Greetings
Jochen

My blog about Win32 and .NET
http://blog.kalmbachnet.de/
 

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