跨DLL的内存/堆管理 [英] Memory / heap management across DLLs

查看:118
本文介绍了跨DLL的内存/堆管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然这似乎是一个很常见的问题,但是我没有收获很多信息:如何在内存分配的DLL边界之间创建一个安全的界面?



在$ a
中,

  // DLLEXPORT MyObject * getObject(){return new MyObject( ); } 
//在DLL中b
MyObject * o = getObject();
delete o;

可能会导致崩溃。
但是,由于像上述那样的交互 - 是不常见的,所以必须有一种方法来确保安全的内存分配。



当然,可以在DLL中提供

 $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b;;;;;;;;; ORT ORT; ORT ORT ORT ORT ORT ORT ORT ORT ORT ORT ORT ORT ORT } 

但也许有更好的方法(例如smart_ptr?)。我在阅读关于在处理STL容器时使用自定义分配器。



所以我的询问更多的是关于文章和/或文学交易的一般指针使用此主题 。有没有特别的谬误去寻找(异常处理?),这个问题仅限于DLL或UNIX共享对象侮辱?

解决方案

如您所建议的,您可以使用 boost :: shared_ptr 来处理这个问题。在构造函数中,您可以传递自定义清理功能,这可以是创建指针的dll的deleteObject-Method。示例:

  boost :: shared_ptr< MyObject>实例(getObject(),deleteObject); 

如果您不需要dll的C-Interface,则可以使用 getObject 返回一个shared_ptr。


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?

It is quite well-known that

// 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.

Of course, one could provide

// in DLL a
DLLEXPORT void deleteObject(MyObject* o) { delete o; }

but maybe there are better ways (e.g. smart_ptr?). I read about using custom allocators when dealing with STL containers as well.

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?

解决方案

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.

这篇关于跨DLL的内存/堆管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆