它是安全的外部的dll缓冲区分配内存,并使用它主要应用? [英] Is it safe to allocate memory for buffers on external dll and use it on main application?

查看:195
本文介绍了它是安全的外部的dll缓冲区分配内存,并使用它主要应用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为主题。我已经找到了这样的事情在一个应用程序。在主要的C应用程序,我们必须声明:

As in topic.. I've found something like this in one application. In main C application we have declaration:

void* buff = NULL;

后来有一个叫:

ReadData(&buff);
SaveToFile(buff);

的SaveToFile()是主要功能的C函数。

READDATA(无效*。*)是外部DLL C ++函数。在缓冲区此功能的内存是由的malloc 函数分配和数据归档。

ReadData(void* * ) is a C++ function from external dll. In this function memory for buffer is allocated by malloc function and filed with data.

因此​​,这里是我的问题:是不是正确的。

So here is my question: is it correct?

推荐答案

在运行的过程中共享所有模块相同的地址空间(不关心你是否是Windows或Linux或任何实际,这是一个共同的原则)。但是,要小心:读取或从模块A写入由模块B所拥有的缓冲区是好的 - 但释放缓冲区可能是坏的。

All modules in a running process share the same address space (doesn't care whether you're Windows or Linux or whatever actually, it's a common principle). However, be careful: reading or writing from module A to a buffer owned by module B is fine - but freeing the buffer is probably bad.

在Windows上,这取决于运行时库应用程序对链接。如果不是该DLL运行时(多线程的dll的),每个模块都维护自己的堆管理器的副本。因此,分配的内存区域中的模块还必须负责,因为只有它自己的堆管理器知道它摧毁它。如果按照这个准则,你将不会遇到问题(联对DLL运行避免了问题,因为所有的模块处理居住某处msvXXXnnn.dll同一个堆管理器,但会引起其它问题)。

On Windows, it depends on the runtime library the application is linked against. If it is not the DLL runtime ('multithreaded dll'), every module maintains its own copy of the heap manager. Thus, the module that allocated a memory area must also be responsible for destroying it because only its own heap manager knows about it. If you follow this guideline, you won't run into problems (linking against the DLL runtime avoids the problem because all modules deal with the same heap manager residing somewhere in msvXXXnnn.dll, but gives rise to other issues).

编辑:

READDATA(无效*。*)从外部DLL C ++函数。在缓冲区此功能的内存是由malloc函数分配和数据归档。

ReadData(void* * ) is a C++ function from external dll. In this function memory for buffer is allocated by malloc function and filed with data.

这可能会遇到上述问题分配器。无论是添加其他功能的DLL( FreeData ),这是释放缓冲区(所建议的尼尔·巴特沃思),只是称自己的明确责任免费()。或者你添加一个DLL函数查询缓冲区的大小,分配它的前期并将其传递到 READDATA (这是国际海事组织最干净的选择)。

That might run into the aforementioned allocator issue. Either add another function to that DLL (FreeData) which is explicitly responsible for freeing up the buffer (as proposed by Neil Butterworth) and just calls its own free(). Or you add a DLL function to query the size of the buffer, allocate it upfront and pass it to ReadData (that's the cleanest choice imo).

这篇关于它是安全的外部的dll缓冲区分配内存,并使用它主要应用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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