在 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 are some reasons for having the caller supply a pointer:
- 对称所有权语义.其他几个答案已经解释了这一点.
- 避免分配器和解除分配器不匹配.如美学家的回答中所述,如果 DLL分配一个指针并返回它,调用者必须调用相应的释放器来释放它.这不一定是微不足道的:DLL 可能静态链接到一个版本,例如
malloc
/free
而.exe
链接到malloc
/free
的不同版本.(例如,DLL 可能使用发布版本,而.exe
使用专门的调试版本.) - 灵活性.如果 DLL 用于一般用途,则让调用方分配内存可为调用方提供更多选择.假设调用者不想使用
malloc
而是希望从某个特定的内存池分配内存.也许在这种情况下,调用者可以提供指向堆栈上分配的内存的指针.如果 DLL 自己分配内存,则调用者没有任何这些选项.
- Symmetric ownership semantics. This is already explained by several other answers.
- 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 ofmalloc
/free
. (For example, the DLL could be using release versions while the.exe
is using specialized debug versions.) - 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 代码使用来解决.)
(The second and third points also mostly can be addressed by having the .exe
supply an allocator/deallocator for the DLL code to use.)
相关文章