Memory / heap management across DLLs
Some pointers:
- Allocating and freeing memory across module boundaries
- STL containers across DLL boundaries
Overload operator new
, operator delete
et. al for all your DLL classes and implement them within the DLL:
void* MyClass::operator new(size_t numb) {
return ::operator new(num_bytes);
}
void MyClass::operator delete(void* p) {
::operator delete(p);
}
...
This can easily be placed in a common base class for all classes exported by the DLL.
This way, allocation and deallocation are done entirely on the DLL heap. Honestly, I'm unsure whether it has any serious pitfalls or portability issues - but it works for me.
You may state that it "might certainly lead to crashes". Funny - "might" means the exact opposite of "certainly".
Now, the statement is mostly historical anyway. There is a very simple solution: Use 1 compiler, 1 compiler setting, and link against the DLL form of the CRT. (And you can probably get away skipping the latter)
There are no specific articles to link to, as this is a non-problem nowadays. You'd need the 1 compiler, 1 setting rule anyway. Simple things as sizeof(std::string)
depend on it, and you'd have massive ODR violations otherwise.
As you suggested, you can use a boost::shared_ptr to handle that problem. In the constructor you can pass a custom cleanup function, which could be the deleteObject-Method of the dll that created the pointer. Example:
boost::shared_ptr< MyObject > Instance( getObject( ), deleteObject );
If you do not need a C-Interface for your dll, you can have getObject
return a shared_ptr.