问题描述:
最近遇到一个问题,编写了一个Dll,然后在exe程序中调用该Dll,代码如下:
/************************************************************************/ /* Dll头文件声明 */ /************************************************************************/ #ifndef TEST_H_ #define TEST_H_ #include <string> using namespace std; #ifdef DLL1_API #else #define DLL1_API _declspec(dllimport) #endif class DLL1_API Test { public: Test(); ~Test(); //const char* GetError(); //DLL中尽量不要导出string,使用char*代替 string GetError(); private: string strError; }; #endif #define DLL1_API _declspec(dllexport) #include "test.h" /************************************************************************/ /* Dll实现 */ /************************************************************************/ Test::Test() { strError = "123456789012345"; }; Test::~Test() { } //const char* Test::GetError() //{ // return strError.c_str(); //} string Test::GetError() { return strError; } /************************************************************************/ /* Dll测试exe程序 */ /************************************************************************/ #include "test.h" #include <iostream> using namespace std; void main(void) { Test test; cout<<test.GetError()<<endl; }
该代码在Test的构造函数中给strError 赋值,当该串的长度小于等于15时(例如:strError = "123456789012345";)程序运行正常;当该串的长度超过15时(例如:strError = "1234567890123456";)时,
程序运行时会崩溃,出错画面如下:
原因分析:
该问题主要是由于在Dll中导出STL造成的,因为DLL和EXE的内存分配方式不同,DLL中的分配的内存不能在EXE中正确释放掉。
解决办法:
1. 设置Dll和exe程序的运行时库,下面是验证过的可以正确运行的组合方式
DLL EXE
/MDd /MDd
/MD /MDd
/MD /MD
/MDd /MD
2.将Dll中Test类导出函数GetError()返回值由string改成char*,如上面代码中注释部分
建议:
在DLL中尽量不要在导出接口中使用string作为输出和输入参数,而改用char*代替
参考:
关于该问题的描述可以参考如下几篇文章:
http://blog.csdn.net/ytfrdfiw/archive/2008/01/17/2048605.aspx
http://topic.csdn.net/t/20050305/22/3827606.html
http://topic.csdn.net/u/20080515/10/BA1CD6B0-FDAE-4898-892C-63E5AC829381.html