You don't need to. Native objects are stored in memory which is not managed by the .NET garbage collector -- they won't be moved around, and pinning would have no effect.
Simply
ManagedFoo()
{
NativeFooFactory factory; // fixed most-vexing parse
myFoo = factory.CreateFoo();
}
should be sufficient.
Or even better
ManagedFoo()
: myFoo{NativeFooFactory().CreateFoo()}
{
}
UPDATE: Since we find out the object can't outlive its factory,
ManagedFoo()
: myFooFactory{new NativeFooFactory()}
, myFoo{myFooFactory->CreateFoo()}
{
}
Although I would suggest some sort of smart pointer to make sure the native objects are correctly freed, perhaps my clr_scoped_ptr
.