Firing an event that returns an array

W

Wild Wind

Hello,

I'm still trying to get to grips with managed C++.

I want to raise an event RaiseEvent which has as one
of its arguments a managed array.

The event will be raised in a function Func which will
take in an instance of an unmanaged class ByteArray.

ByteArray essentially wraps an array of bytes
(or chars) which you get using a serialize method, and
whose length you find out using the size method.

Here is my attempt below:

void Func(ByteArray ba)
{

int arrLen = ba.size();

System::Byte __pin baArray __gc[] = new System::Byte[arrLen];

char* baArray2 = &baArray[0];

ba.serialize(baArray2);

RaiseEvent(baArray);
}

What I am confused about is whether I need to put the __gc
in front of the array baArray that I will be passing in
RaiseEvent, or whether I have missed it elsewhere. I'm
also not sure whether I need to pin the array - I think
I should because I will be passing it to a function of
an unmanaged class.

Any clarification would be appreciated.
 
J

Jesse McGrew

Wild said:
void Func(ByteArray ba)
{

int arrLen = ba.size();

System::Byte __pin baArray __gc[] = new System::Byte[arrLen];

char* baArray2 = &baArray[0];

ba.serialize(baArray2);

RaiseEvent(baArray);
}

What I am confused about is whether I need to put the __gc
in front of the array baArray that I will be passing in
RaiseEvent, or whether I have missed it elsewhere. I'm
also not sure whether I need to pin the array - I think
I should because I will be passing it to a function of
an unmanaged class.

I believe the __gc keyword is optional in baArray's declaration, since
you used the .NET type name System::Byte instead of the C++ type name
unsigned char.

Pinning is something you do to pointer variables, not array variables -
whenever you hold a pinning pointer to some managed memory, the garbage
collector won't touch that memory. Take the __pin keyword out of
baArray's declaration, and put it in baArray2's declaration.

It might also be a good idea to unpin the array (set baArray2 to NULL)
after calling ba.serialize(), so the GC can move the array if it needs
memory while RaiseEvent is executing.

Jesse
 

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