C++/CLI norms for calling functions that want String ^ when you have native char *

  • Thread starter Thread starter Bern McCarty
  • Start date Start date
B

Bern McCarty

In MEC++ I could just call a function that was expecting a String __gc* even
though I had a native char *. The char * automatically got marshaled to a
String __gc*.

In the May CTP of VS 2005 I just get a compile-time error: cannot convert
parameter 1 from 'char *' to 'System::String ^'

What would be the normal C++/CLI way to handle this? And can I do it that
way in the May CTP?

I thought it might be the marshal_as template but I couldn't really find it
or enough information about it.

Bern McCarty
Bentley Systems, Inc.
 
Bern McCarty said:
In MEC++ I could just call a function that was expecting a String __gc* even
though I had a native char *. The char * automatically got marshaled to a
String __gc*.

In the May CTP of VS 2005 I just get a compile-time error: cannot convert
parameter 1 from 'char *' to 'System::String ^'

What would be the normal C++/CLI way to handle this? And can I do it that
way in the May CTP?

I use:

System::String * DotNetStringFromSTLString( const std::string &string_ )
{
return Marshal::PtrToStringAnsi((int*) string_.c_str());
}

which works, but for all I know is leaking like a swimming pool full of
porcupines.
 
Do this :-

ref class R
{
public:
void Test(String^ s)
{
}
};

void _tmain()
{
R^ r = gcnew R();
char* s = "hello world";
r->Test(gcnew String(s));
}
 
Hi Steve

There is no leak, since PtrToStringAnsi creates a new String object and
copies the source string into it. The managed String object will get GC'd
eventually.
 
Back
Top