如何从dll中返回std::string类型的字符串,内详!

xxllaaa 2004-11-14 05:20:01
我在dll中定义一个函数如下
std::string __stdcall GetDllString()
{
std::string str = "hello?";

return str;
}
该函数只是简单的返回一个字符串,我在应用程序中以如下方式调用
void CTest_common_dllDlg::OnBtnConvert()
{
std::string str;
typedef std::string (__stdcall* PFN_GETSTRING)();
HINSTANCE hInst = LoadLibrary("dll.dll");
if (hInst) {
PFN_GETSTRING pfnGetString = reinterpret_cast<PFN_GETSTRING>(GetProcAddress(hInst, "GetDllString"));
if (pfnGetString) {
str = pfnGetString();
}
}
MessageBox(str.c_str());

FreeLibrary(hInst);
}

但是在该按钮函数运行结束后就会发生内存不能为read的错误!

请问各位大侠,这个问题该如何解决,100分不成敬意!
...全文
956 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
xxllaaa 2004-11-18
  • 打赏
  • 举报
回复
谢谢各位!每人都又分!
freefalcon 2004-11-18
  • 打赏
  • 举报
回复
主要是因为DLL和应用程序使用了不同的堆,string由DLL分配,却由应用程序释放,因此发生错误

修改一下DLL和应用程序的设置即可

选择project>settings>c/c++>code generation下的using run-time library为
multithreaded dll, Debug版则选debug multithreaded dll
vcforever 2004-11-18
  • 打赏
  • 举报
回复
补充:MessageBox行去掉!
:)
vcforever 2004-11-18
  • 打赏
  • 举报
回复
在DLL中
std::string* __stdcall GetDllString()
{
return new std::string("hello");
}

void __stdcall ReleaseDllString(std::string* pStr)
{
delete pStr;
pStr = NULL;
}

void CTest_common_dllDlg::OnBtnConvert()
{
std::string* pstr;
typedef std::string* (__stdcall* PFN_GETSTRING)();
typedef void (__stdcall * PFN_RELEASE)(std::string*);
HINSTANCE hInst = LoadLibrary("dll.dll");
if (hInst) {
PFN_GETSTRING pfnGetString = reinterpret_cast<PFN_GETSTRING>(GetProcAddress(hInst, "GetDllString"));
PFN_RELEASE pfnReleaseString = reinterpret_cast<PFN_RELEASE>
(GetProcAddress(hInst, "ReleaseDllString"));
if (pfnGetString && pfnRelease) {
pstr = pfnGetString();
}
pfnRelease(pstr);
}
MessageBox(str.c_str());

FreeLibrary(hInst);
}

就可以了!楼主可以试一试!
cnss 2004-11-18
  • 打赏
  • 举报
回复
这样的话,你用VC编译的DLL就只能让VC编译的程序调用了
shornmao 2004-11-17
  • 打赏
  • 举报
回复
STL中的很多类型都不适合通过DLL传递,不管是参数还是返回值。
这种情况下,推荐返回C风格字符串,有需要的话,在调用端再用返回值初始化std::string
sinall 2004-11-15
  • 打赏
  • 举报
回复
确实应该是临时变量的问题。
应该采用堆分配。
keiy() 的办法试试。

传个参数进去,然后赋值。不要用return了。
doolin 2004-11-14
  • 打赏
  • 举报
回复
返回一个局部对象的引用或指针是在函数返回时,对象就不存在了。对返回对象是可以的,因为它会产生一个拷贝。如果连局部对象都不能返回的话,那函数的返回值的意义是什么?
象下面这样:
int foo()
{
int temp;
// do something with temp;
return temp;
}

这样怎么有错,所以楼主的写法并不是返回局部对象的问题。
柯本 2004-11-14
  • 打赏
  • 举报
回复
试试:
std::string __stdcall GetDllString()
{
static std::string str = "hello?";

return str;
}
beyondtkl 2004-11-14
  • 打赏
  • 举报
回复
可以做为传入参数 然后再DLL里修改 在传回。。

或者 分配全局的内存
oyljerry 2004-11-14
  • 打赏
  • 举报
回复
临时变量,返回后,不存在了,当然不能read了
用堆传递
roscoe 2004-11-14
  • 打赏
  • 举报
回复
你返回的是临时变量,传一个缓冲区进去把它拷贝出来

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧