我正在使用动态加载 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:
malloc
/free
而 .exe
链接到malloc
/free
的不同版本.(例如,DLL 可能使用发布版本,而 .exe
使用专门的调试版本.)malloc
而是希望从某个特定的内存池分配内存.也许在这种情况下,调用者可以提供指向堆栈上分配的内存的指针.如果 DLL 自己分配内存,则调用者没有任何这些选项.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.)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.)
这篇关于在 DLL 中分配内存并将指向它的指针指向客户端应用程序是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!