Marshal.Copy

E

eusebiu

Hello.... I have an MFC ActiveX and creates a BYTE* buffer(as a
CDialog Class member) and I've wrote a function that gets the pointer
to that buffer and it's size:
void CMainDialog::GetPointers(int *p, int *size)
{
if(buffer != NULL)
{
delete buffer;
buffer = NULL;
}

buffer = new BYTE[10];
memset(buffer, 1, 10);

*p = (int)buffer;
*size = 10;
}
After this method is called, I fire an event to notify the web to get
my pointers.

void CMyActiveXCtrl::LoadParameter(void)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());


m_MainDialog.GetPointers(&this->p, &this->size);

// Fire an event to notify web page
FireParameterLoaded();
}

In my JavaScipt code, I send via Ajax.NET the values to server side.
On server side I receive them very well... but when I try to make them
managed, the system fails.

If I use:
byte[] buffer = new byte[size];
Marshal.Copy((IntPtr)pointer, signature, 0, size); I get an
exception... an ugly one :
"Attempted to read or write protected memory. This is often an
indication that other memory is corrupt." and the LastWin32Error is
1008:
ERROR_NO_TOKEN
1008 An attempt was made to reference a token that does not exist.
this makes me thinks that the buffer is deleted from the unmanaged
side memory...

I want to know... How can I send a BYTE* buffer from unmanged code to
managed? The above solution is with pointes.
One other solution is to use CString class.. but if I have a 0
characher inside the buffer, I won't get the whole buffer(I've tried
this solution only on non-zero buffers.. and it works).

Thanks
 
N

Nicholas Paldino [.NET/C# MVP]

You have some problems here.

First, when you are returning memory from COM methods, you are supposed
to use the COM allocator, either through CoTaskMemAlloc, or by obtaining the
allocator interface (IMalloc, CoTaskMemAlloc actually gets this interface to
allocate memory). In calling new, you are violating the memory model of
COM, and you are actually creating a memory leak, as you have no way of
calling delete to release the pointer in memory.

Instead, if you want COM to handle this for you, and also want it to be
available to Automation clients (as well as make it easy to use in .NET),
you should use a SAFEARRAY and pass that back.
 

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