Reputation:
I was doing some C++/CLI programming recently in order to integrate some of our company's native C++ classes into .NET. My question may sound trivial, but this is one thing I'm always not sure about:
If there is a ref class with a native pointer, say
public ref class ManagedClass {
private:
NativeClass* pObj1;
NativeClass* pObj2;
void DoStuff(NativeClass* obj);
public:
ManagedClass();
bool Activate();
}
and a constructor like
ManagedClass::ManagedClass() : pObj1(new NativeClass()), pObj2(new NativeClass()) {;}
instances of that class will be created on the managed heap. However, pObj1
and pObj2
do point to objects created on the native heap? So there is no pinning needed to use those pointers, even since they are members of a managed class? Especially, if the DoStuff
function calles a external native library function, say
void ManagedClass::DoStuff(NativeClass* obj) {
int returnCode = External::Function(obj);
if (returnCode == 0) return true;
else return false;
}
is there no need to write something like pin_ptr<NativeClass> pinPtr = obj
etc.? I guess the situation is different if a reference to the pointer is needed; here, however, I understand that the location of the pointer itself may vary due to memory reallocation, but its content, i.e. a memory adress on the native heap, stays valid since the garbage collector won't touch that memory. Is this correct and code like the one above safe to use?
Thanks for your help!
Matthew
Upvotes: 2
Views: 2435
Reputation: 2579
To your question the code you posted is correct and will work.
In my opinion it would be preferable(cleaner\safer) to use C++\CLI as a wrapper to your C++ native classes so all the public methods should receive only managed objects as parameters otherwise just use COM
Upvotes: 1