tags:

views:

210

answers:

2

Hi,

I am working in mixed mode (managed C++ and C++ in one assembly). I am in a situation something like this.

ManagedStructure ^ managedStructure = gcnew ManagedStructure();
//here i set different properties of managedStructure 

then I call "Method" given below and pass it "& managedStructure"

Method(void *ptrToStruct)
{
    ManagedStructure ^ managedStructure2 = gcnew ManagedStructure();
    memcpy(&managedStructure2 , ptrToStruct, sizeof(managedStructure2 ));
}

I have following question about this scenario.

1) Is it safe to use memcpy like this? and if not what is its alternate to achieve same functionality? ( I can't change "Method" definition)

2) I am not freeing any memory as both the structures are managed. Is it fine?

+1  A: 

You could look into using a copy constructor or something similar. Check out this article as it explains a few things that might be useful.
I would assume your memory model is OK since it's all managed.

SB
+1  A: 

I'm not sure but you might need to pin managedStructure2 before the memcpy, look at the docs for pin_ptr<>. If it's not pinned, GC might happen on a separate thread in the middle of your memcpy, resulting in an intermittent bug.

Peter Hull
I am having some trouble in pinning the pointer. Can u help me out here? How can I pin managedStructure2?
Haris Hasan