DLL的灾难---DEBUG与RELEASE版本不能交叉调用

来源:互联网 发布:网络理财诈骗案 编辑:程序博客网 时间:2024/05/01 09:36
让我们先看一段引文,再来进行心灵的探索:

If you have an EXE and a DLL.

When your exe APP was built Debug Mode, your Dll must be Debug mode. 

When your exe APP was built Release Mode, your Dll must be Release mode. 

If exe is Release Mode and Dll is Debug Mode, Error. 

If exe is Debug Mode and Dll is Release Mode, Error.

-------------------------------- Why? --------------------------------

Looks like you have a problem with memory allocation.

When an application is built in debug mode it does not allocate memory from the same heap as it does in release mode.(have a look to the definition of new and delete operator, and also to malloc (in afxmem.h ? (not sure just grep it))

Thus, when you get some memory from your debug app and give this memory to your release dll for processing and FREEING,you get an error since the realase dll tries to free it from the wrong heap. So always use your app and dll in the same mode. 

At least, do not try to free memory allocation in one mode in the other mode.


现在,我们来概括一个结论:

之所以,Dll与Exe之间进行Release与Debug的交叉调用会出现错误,一个非常重要的原因,可能是由于Debug下与Release下,模块的导入地址是不一样的,即使你取消所有的优化,也许也并不能改变这样的结局。 从而对于一个在Exe(假如是Release版本)中生成的对象(比如一个静态的全局数组),与一个在Dll中生成的对象可能会位于完全不同的内存区域,从而对那些借助于对静态指针的值进行判断的类(比如CString)跨模块调用的时候,一旦出现判断,将会出现严重的逻辑错误,从而使一块本不该被释放的内存被释放,从而引发运行时的错误。

解决交叉调用的最简单,最合理的方法就是: debug调用debug版,release调用release版,这也许就是模块化中的一个瑕疵吧。

---------------------------------------------------------------------------------------------------------------------------------------------------------------

原文地址:http://hi.baidu.com/idealsoft/blog/item/f7bdd7d7e8ac19d8a044df7f.html

原创粉丝点击