在DLL中分配内存并将其指向客户端应用程序是不好的做法吗? [英] Is it bad practice to allocate memory in a DLL and give a pointer to it to a client app?

查看:98
本文介绍了在DLL中分配内存并将其指向客户端应用程序是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用动态加载DLL的exe。 DLL中的函数分配堆上的内存并将指向该内存的指针传递给exe。

I'm using an exe which dynamically loads a DLL. A function in the DLL allocates memory on the heap and passes a pointer to that memory to the exe.

一个大四学生说,这是不好的做法。他说如果我必须在exe和DLL之间共享内存,exe必须分配内存并传递一个指向DLL的指针,反之亦然。这是真的?为什么?

A senior says that it is bad practice to do so. He says that if I ever have to share memory between the exe and the DLL, the exe has to allocate memory and pass a pointer to that to the DLL, and not vice versa. Is this true? Why?

编辑:在我的例子中,我计划在DLL本身内部分配和释放内存。

In my case, I planned to allocate and deallocate memory inside the DLL itself.

推荐答案

这里有一些原因让调用者提供一个指针:

Here some reasons for having the caller supply a pointer:


  1. 对称的所有权语义。 strong>这已经通过几个其他答案解释。

  2. 避免分配器和释放器不匹配。 Esthete的回答,如果DLL分配一个指针并返回它,调用者必须调用相应的释放器释放它。这不一定是微不足道的:DLL可能静态链接到一个版本,例如, malloc / free .exe 与不同版本的 malloc / >。 (例如,DLL可能使用发布版本,而 .exe 正在使用专门的调试版本。)

  3. 灵活性。如果DLL是为一般使用,让调用者分配内存,给调用者更多的选择。假设调用者不想使用 malloc ,而是希望从某个特定的内存池中分配内存。也许这是一种情况,调用者可以提供一个指向堆栈上分配的内存的指针。如果DLL分配了内存本身,调用者没有这些选项。

  1. Symmetric ownership semantics. This is already explained by several other answers.
  2. Avoids mismatching the allocator and deallocator. As mentioned in Aesthete's answer, if the DLL allocates a pointer and returns it, the caller must call the corresponding deallocator to free it. This is not necessarily trivial: the DLL might be statically linked against one version of, say, malloc/free while the .exe is linked against a different version of malloc/free. (For example, the DLL could be using release versions while the .exe is using specialized debug versions.)
  3. Flexibility. If the DLL is meant for general use, having the caller allocate the memory gives the caller more options. Suppose the caller doesn't want to use malloc and instead wants memory to be allocated from some specific memory pool. Maybe it's a case where the caller could provide a pointer to memory allocated on the stack. If the DLL allocated the memory itself, the caller does not have any of these options.

(第二和第三点可以通过 .exe 为要使用的DLL代码提供一个allocator / deallocator来解决。)

(The second and third points also mostly can be addressed by having the .exe supply an allocator/deallocator for the DLL code to use.)

这篇关于在DLL中分配内存并将其指向客户端应用程序是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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