Memory / heap management across DLLs(跨 DLL 的内存/堆管理)
问题描述
虽然这看起来是一个很常见的问题,但我并没有收获太多信息:如何在 DLL 边界之间创建一个关于内存分配的安全接口?
Although it seems to be a very common issue, I did not harvest much information: How can I create a safe interface between DLL boundaries regarding memory alloction?
众所周知
// in DLL a
DLLEXPORT MyObject* getObject() { return new MyObject(); }
// in DLL b
MyObject *o = getObject();
delete o;
肯定会导致崩溃.但由于像上面这样的交互 - 正如我敢说的 - 并不少见,因此必须有一种方法来确保安全的内存分配.
might certainly lead to crashes. But since interactions like the one above are - as I dare say - not uncommon, there has to be a way to ensure safe memory allocation.
当然可以提供
// in DLL a
DLLEXPORT void deleteObject(MyObject* o) { delete o; }
但也许有更好的方法(例如 smart_ptr?).我还阅读了有关在处理 STL 容器时使用自定义分配器的信息.
but maybe there are better ways (e.g. smart_ptr?). I read about using custom allocators when dealing with STL containers as well.
因此,我的查询更多是关于关于与该主题相关的文章和/或文献的一般指示.是否有需要注意的特殊谬误(异常处理?)?这个问题是否仅限于 DLL 或 UNIX 共享对象也受到影响"?
So my inquiry is more about general pointers to articles and/or literature dealing with this topic. Are there special fallacies to look out for (exception handling?) and is this problem limited to only DLLs or are UNIX shared objects "inflicted" too?
推荐答案
正如您所建议的,您可以使用 boost::shared_ptr 来处理这个问题.在构造函数中,您可以传递一个自定义清理函数,它可以是创建指针的 dll 的 deleteObject-Method.示例:
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 );
如果你的 dll 不需要 C 接口,你可以让 getObject 返回一个 shared_ptr.
If you do not need a C-Interface for your dll, you can have getObject return a shared_ptr.
这篇关于跨 DLL 的内存/堆管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:跨 DLL 的内存/堆管理
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
