How to convert form Byte pointer to Int16 pointer

  • Thread starter Thread starter Howard Weiss
  • Start date Start date
H

Howard Weiss

I am reading a file (containing short integers). To read the file, I use
the following

FileStream *myFile = new FileStream(FileName, FileMode::Open,
FileAccess::Read);

__int64 myFileSize = myFile->get_Length();

Byte[] myFileData;
myFile1Data = new Byte[myFileSize];
myFile->Read(myFile1Data, 0, myFileSize);

This reads the contents of the file into memory. I would now like to access
the data as an Array of UInt16.

However, Managed C++ does not allow me to perform a simple cast, e.g.

UInt16 *myUInt16 = (UInt16 *) myFileData;

Can I do what I want? If not, why not?

Howard Weiss
 
Howard said:
I am reading a file (containing short integers). To read the file, I use
the following

FileStream *myFile = new FileStream(FileName, FileMode::Open,
FileAccess::Read);

__int64 myFileSize = myFile->get_Length();

Byte[] myFileData;
myFile1Data = new Byte[myFileSize];
myFile->Read(myFile1Data, 0, myFileSize);

This reads the contents of the file into memory. I would now like to access
the data as an Array of UInt16.

However, Managed C++ does not allow me to perform a simple cast, e.g.

UInt16 *myUInt16 = (UInt16 *) myFileData;

Can I do what I want? If not, why not?

You can't just convert managed pointers to unmanaged pointers.

I believe the most simple and fastest method is to create a managed
array, pin it and then use memcpy to copy the data from the buffer to
the managed array:

I use code similar to this in a project of mine:


array<Byte>^ test = gcnew array<Byte>(400);
pin_ptr<Byte> ptrTest = &test[0];
memcpy(ptrTest, _pFileBase, 400);
ptrTest = nullptr;

I'm sorry about the C++/CLI syntax. In MC++ it should be something like
this (untested):

Byte* test[] = new __gc Byte[400]; //??
int __pin* pTest = &test[0];
memcpy(pTest, _pFileBase, 400);
pTest = 0;


If there is a better way to do this, I'd be interested in it as well

Ben
 
Hi,

Following is a Sample of how to manipulate a GC Byte array in unmanaged C++ ( as an 'unsigned short' array ) without copying the content of the array:

virtual int ManipArray(System::Byte btArray __gc[])
{
int i = 0;
BYTE __pin *pbtArray = &btArray[0];
unsigned short *uiArray = (unsigned short*)pbtArray;
for(i; i < btArray->Length/2; i++)
uiArray <<= 1;
return 0;
}

Hope this help...

Nadav
http://www.ddevel.com
 
Back
Top