PN: Managed and Unmanaged Strings

P

Peter Nolan

Hi All,
I have some older C++ code that reads databases via ODBC and converts
data to C++ null delimited strings. I amd writing a tool to read
these types of old C strings and update an XML file.

The XML file is being loaded by managed classes. I want to convert a
c string to a C++.net string class. Or, more correctly, take a C
string and put it into a C++.net string. Something like the following:

char* test_string1

strcpy(test_string1,"This is test string1")

and get it into a structure/array that has String data types....

I've been reading about __box etx but I have not been able to figure
this one out and get it to work. Any/all advice most welcome.

Peter Nolan
 
P

Peter Nolan

Hi All,
just in case it helps someone else...

It turns out that
char* test_string = "This is some text" ;
String * test2 ;
test2 = test_string ;

moved the test_string to test2 string just fine...though I have not
managed to get a managed string back to a non_managed string but it
looks like I could write a function to copy uit our char by char...

Best Regards

Peter Nolan
www.peternolan.com
 
T

Tony Nassar

Peter,

Remember that System::Char is not the same as char. It's a 16-bit character
(or wchar_t). You might get away with copying the characters in a
System::String to a char[], but that would be luck. The code to do this
correctly is below. A System::Byte is an *unsigned* byte; I believe the C++
standard failed to define whether char is signed or unsigned, but it
shouldn't matter (corrections welcome!).

Tony

#using <mscorlib.dll>

using namespace System;

int _tmain()

{

System::String* name = S"Tony Nassar";

System::Char chars __gc[] = name->ToCharArray();

System::Text::ASCIIEncoding* encoding = new System::Text::ASCIIEncoding();

System::Text::Encoder* encoder = encoding->GetEncoder();

int numEncodedBytes = encoder->GetByteCount(chars, 0, name->Length, true);

System::Byte bytes __gc[] = new System::Byte[numEncodedBytes + 1];

encoder->GetBytes(chars, 0, chars->Length, bytes, 0, true);

bytes[numEncodedBytes] = 0; // null-termination, C-style; the CLR seems to
do this for you, actually.

return 0;

}
 

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