Very newbie question about returning strings

G

George

How do I call a function that returns a string in managed C++

This for example is very wrong.


private: System::Void button1_Click(System::Object * sender,
System::EventArgs * e)
{
string str;
str= GetTextMessage;
MessageBox(0,str.data(),"Test",MB_OK);
}

private: System::String GetTextMessage()
{
string str("Hello ");
str+="World";
return str;
}
 
M

Michiel

George said:
How do I call a function that returns a string in managed C++

This for example is very wrong.


private: System::Void button1_Click(System::Object * sender,
System::EventArgs * e)
{
string str;
str= GetTextMessage;
MessageBox(0,str.data(),"Test",MB_OK);
}

private: System::String GetTextMessage()
{
string str("Hello ");
str+="World";
return str;
}

Hi,

I found this a nice experiment for myself (being an old-school C++-er :p)
and I came to the following working solution :

private: System::Void button1_Click(System::Object * sender,
System::EventArgs * e)
{
String* str="con";
str=String::Concat(str, f_ReturnStr());
MessageBox::Show(str);
}


System::String* f_ReturnStr()
{
String* str="cate";
str=String::Concat(str, "nation");
return str;
}

But personally I prefer using CString (include atlstr.h) because of it's +=
operator and it's non-pointer declaration. For some reason, everything in
..Net has to be a pointer.
 
D

Doug Harrison [MVP]

Michiel said:
Hi,

I found this a nice experiment for myself (being an old-school C++-er :p)
and I came to the following working solution :

private: System::Void button1_Click(System::Object * sender,
System::EventArgs * e)
{
String* str="con";
str=String::Concat(str, f_ReturnStr());
MessageBox::Show(str);
}


System::String* f_ReturnStr()
{
String* str="cate";
str=String::Concat(str, "nation");
return str;
}

But personally I prefer using CString (include atlstr.h) because of it's +=
operator and it's non-pointer declaration. For some reason, everything in
.Net has to be a pointer.

The next version of VC.NET will offer a new syntax that distinguishes
between .NET reference types and C++ pointers. System::String is a .NET
reference type, which means it's always referred to through a handle, or
__gc pointer as it's called today. Above, the str variables are really __gc
pointers.

Tip: When working with managed strings, managed string literals are more
efficient than native string literals. Using S"con" and so forth will save
you some implicit conversions that take place under the hood at runtime.
 

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