关于Dll中导出string的问题

问题描述:

最近遇到一个问题,编写了一个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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值