Passing string from C++ code to C#

M

muntyanu

Hi all,

I am passing string from C++ to C# but not sure which way is more
correct. Here it is:
First approach:
CDAnetCSharpHooks::passString( )
{
char str[] = "String to pass";
DotNetObject *obj = new DotNetObject();
obj->UseStringInDotNet( str );
}

Second approach:
CDAnetCSharpHooks::passString( )
{
char str[] = "String to pass";
CString temp(str);
System::String * dotNetStr = new System::String( temp);
DotNetObject *obj = new DotNetObject();
obj->UseStringInDotNet( dotNetStr );
}

C# method
public void UseStringInDotNet( String str )
{
// create new thread and use string in it
}

UseStringInDotNet() is creating new thread and that is why PassString()
will finish its work before UseStringInDotNet() finishes its own.
Basically first approach is working, but sometimes on the .NET side I
have some unpredictable behaviour in memory. I am wondering if that
memory for str buffer is cleared before C# get its work done. In this
respect will be the second approach more safe ?

Thank you very much in advance for any suggestions

Roman
 
D

Dmytro Lapshyn [MVP]

Hi,

This actually belongs in microsoft.public.dotnet.framework.interop, but I'll
answer here.

I am not sure system::string can be properly marshalled to the managed
world. As far as I remember it is able to cast itself either to char* or to
wchar_t* (I believe the marshaler can understand both), but I'd better stick
with explicit char*. Even better, use the OLEView tool to examine the C#
server's type library and to find out which flavor of string it expects
(might be BSTR, for example).

Memory management can be nasty. I'd recommend that you check with MSDN re
memory management conventions applicable to the flavor of string you use. It
is quite common for the caller to allocate the memory and for the callee to
free it when no longer needed. Again, please read documentation on COM
interop marshalling carefully.

See here for example:

http://msdn.microsoft.com/library/d...ide/html/cpcondefaultmarshalingforstrings.asp

and

http://www.develop.com/conferences/conferencedotnet/materials/C8.pdf (pages
7 and 8)
 

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