Convert wchar_t 40 to System:String gives length 43?

  • Thread starter Thread starter Sascha Fuchs
  • Start date Start date
S

Sascha Fuchs

Hello,

I'am currently on a project where I have to mix managed and unmanaged code,
but now I found something odd.

I have some code where I need to convert a "wchar_t name[40]" to a
System::String, but after the conversion the string has a length of 43 where
the first 40 characters are from the name plus 3 "garbage" characters.

For example "Assmann Muehlen "
becomes "Assmann Muehlen é¡ëŒ…趯".

The code looks like this and is meant for 64Bit:

wchar_t name[40];
RfcGetChars(row, iU("NAME"), name, sizeofU(name), &errorInfo);
//name has now the value "Assmann Muehlen "
//new customer object
Customer ^cust = gcnew Customer();
cust->name = gcnew String(name);
//cust->name has now the value "Assmann Muehlen é¡ëŒ…趯"
cust->name = String(name, 0, sizeofU(name));
//now the value of cust->name is "Assmann Muehlen "
//but I still find it odd
customers->Add(cust);

The customer class is defined like this:
public ref class Customer
{
public:
System::String ^name;
};

Any ideas or is String(name, 0, sizeofU(name)) the only solution?

Sascha
 
Hi Sascha!
For example "Assmann Muehlen "
becomes "Assmann Muehlen é¡ëŒ…趯".

The code looks like this and is meant for 64Bit:

wchar_t name[40];
RfcGetChars(row, iU("NAME"), name, sizeofU(name), &errorInfo);
//name has now the value "Assmann Muehlen "

No. This onyl seems to be so ;)
In reallity it has 40 wchar_ts! And it is not a string, because it is
*not* NUL-terminated...
//new customer object
Customer ^cust = gcnew Customer();
cust->name = gcnew String(name);

This assumes that the string IS NUL terminated, which is not in your
case. Therefor it will append a *string* as long as a NUL character
appears..
cust->name = String(name, 0, sizeofU(name));
//now the value of cust->name is "Assmann Muehlen "

Yes. That is expected. You not explitcit tell the constructor, that the
string has 40 characters! and is NOT NUL terminated ;)

--
Greetings
Jochen

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