Codwiz51's Wiki

RSS

Navigation







Quick Search
»
Advanced Search »

Or, How to convert between a native unicode string and a managed byte array

Update: I've expanded this work on my web site. I've written new articles at My C++/CLI work

I've been playing around with manipulating managed byte arrays and native strings. It's possible to do a number of useful transformations between the two types in C++/CLI mixed mode programming.

Here is one example, compiled using Unicode character sets:
 // Create a pointer to a native string
 LPTSTR strT = _T("This is a test string.");
 
 // Create an empty byte array
 array<unsigned char>^ pBuf = gcnew array<unsigned char>(100);

 // Create a pinned pointer to the first byte in the array
 pin_ptr<unsigned char> ptrBuf = &pBuf[0];

 // Assign the pointer to a native byte pointer
 LPBYTE lpBuf = ptrBuf;

 // Copy the native string to the byte array
 memcpy(lpBuf, strT, sizeof(TCHAR) * _tcslen(strT));

 // Get a reference to the string
 String^ tT = Encoding::Unicode->GetString(pBuf, 0, sizeof(TCHAR) * _tcslen(strT));

 // tT now points to a String containing "This is a test string."

The above code isn't too exciting. (Nach!)

However, we now have the possibility of loading a native struct into a managed byte array using a fast memcpy call rather than a slow Marshal::Copy call. The important point of these experiments? We might be able to place a native struct in a ref class and then load it by performing a memcpy operation. Now this might make things a lot faster without a lot of marshaling code.

For operations like FindFirstFile and FindNextFile API calls using P/Invoke, maybe we can speed them up a little? First, here is an example of an inefficient means of locating files in this article.

ScrewTurn Wiki version 3.0.2.509. Some of the icons created by FamFamFam.