Casting different base-type managed buffers

?

.

Hello

I am migrating a VC6 C++ library to VC7 Managed C++.

I need to iterate along a buffer of unsigned shorts, char-by-char:

unsigned short lpData __gc[];
unsigned char __gc * itr = NULL;

lpData = new unsigned short __gc [1000];
itr = __try_cast< unsigned char __gc *>( &lpData[0] ); <<<<<<< C2440 !!!

for( unsigned long i=0; i<1000; i++ )
{
itr++;
}

Any ideas ?

Thanks in advance,
ívan
 
B

Brandon Bray [MSFT]

Hello!
I need to iterate along a buffer of unsigned shorts, char-by-char:

I'm not sure why you would want to iterate an array of shorts a character at
a time. Wouldn't you want to iterate an array a short at a time? It would
appear that is what you meant to do. Otherwise your for loop would only
iterate over half the array. If I am right, the following code compiles and
does what you want:

unsigned short lpData __gc[];
unsigned short __gc * itr = NULL;

lpData = new unsigned short __gc [1000];
itr = &lpData[0];

for( unsigned long i=0; i<1000; i++ )
{
itr++;
}

If you really do want to iterate over the array character by character, than
you need to use reinterpret_cast as what you are doing is fundamentally not
type safe. Think twice as this is dangerous. Anyways, here's an example:

UInt16 arr[] = { 0, 1, 2, 3 };
Byte* itr = reinterpret_cast<Byte*>(&arr[0]);

for(int i=0; i<8; i++) {
Console::WriteLine(*itr++);
}

Cheerio!
 

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