Converting an array to a buffer

G

Guest

Hi.

I'm developing an application using managed C++. My application has to use a
DLL developed in standard C++. The mentioned DLL implements a class for file
operations. There is a class method uses a pointer to a buffer (e.g. BYTE
*pBuf = new BYTE [1024]) as input / output.

My program has to serialize a 'ref class MyClass' and store it in the file
using the mentioned DLL API. Another invocation of the program has to
deserialize the prior stored data.

I'm able to serialize the class using BinaryFormatter() and MemoryStream().
My problem is that serialized data are stored in an array (see below).
Simillary the deserialization uses an array as input. The point is that I'm
unable to extract the data buffer from the array.

Code:
----
MyClass^ myObj;
...
IFormatter^ formatter = gcnew BinaryFormatter();
MemoryStream^ msSer = gcnew MemoryStream();
formatter->Serialize(msSer, myObj);
msSer->Seek(0, SeekOrigin::Begin);
array<Byte>^ dataArray = gcnew array<Byte>(msSer->Length);
int dataArrayLen = msSer->Read(dataArray, 0, msSer->Length);
// -- I need to fill this buffer --
BYTE *pBuf = new BYTE [msSer->Length];

// -- This trick doesn't work of course --
pBuf = reinterpret_cast<BYTE *>(&dataArray);

MemoryStream^ msDeser = gcnew MemoryStream(dataArray, 0,
dataArray->Length, false);
MyClass^ myObjOut = (MyClass^) formatter->Deserialize(msDeser);
 
S

SvenC

Hi Damir,

Damir Dezeljin said:
Hi.

My program has to serialize a 'ref class MyClass' and store it in the file
using the mentioned DLL API. Another invocation of the program has to
deserialize the prior stored data.

I'm able to serialize the class using BinaryFormatter() and
MemoryStream().
My problem is that serialized data are stored in an array (see below).
Simillary the deserialization uses an array as input. The point is that
I'm
unable to extract the data buffer from the array.

Code:
----
MyClass^ myObj;
...
IFormatter^ formatter = gcnew BinaryFormatter();
MemoryStream^ msSer = gcnew MemoryStream();
formatter->Serialize(msSer, myObj);
msSer->Seek(0, SeekOrigin::Begin);
array<Byte>^ dataArray = gcnew array<Byte>(msSer->Length);
int dataArrayLen = msSer->Read(dataArray, 0, msSer->Length);
// -- I need to fill this buffer --
BYTE *pBuf = new BYTE [msSer->Length];

// -- This trick doesn't work of course --
pBuf = reinterpret_cast<BYTE *>(&dataArray);

pin_ptr<BYTE> p = &dataArray[0]; // get a native pointer to byte array
int cb = (long)msSer->Length; // won't work correctly for arrays larger than
2GB
memcpy_s(pBuf, cb, p, cb);
 

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