从 DLL 函数返回字符串 [英] Returning Strings from DLL Functions

查看:27
本文介绍了从 DLL 函数返回字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,从 DLL 函数返回一个字符串会导致我的程序在运行时崩溃,并出现错误.

我已经通过将 DLL 代码编译为 .exe 并在 main 函数中做一些简单的测试来验证它不是函数本身的问题.>

具有其他返回类型(intdouble 等)的函数可以完美运行.

  • 为什么会发生这种情况?
  • 有没有办法解决这种行为?

DLL 的源代码:

//库.h#include <字符串>std::string GetGreeting();

.

//库.cpp#include "Library.h";std::string GetGreeting(){return 你好,世界!";}

测试人员的源代码:

//Tester.cpp#include #include int main(){std::cout <<获取问候()}

我使用的是 VS2010.


结论

解决方法是确保使用相同编译器相同选项等编译库和源代码.

解决方案

由于您的错误消息表明您使用的是 Microsoft C++,因此我将提供特定于 MS 的答案.

只要您使用相同的编译器编译 EXE 和 DLL,并且两者都动态地链接相同版本的运行时,那么您就可以了.例如,对两者都使用多线程 DLL".

如果您静态链接运行时,或者链接到不同版本的运行时,那么您就是 SOL,原因是@Billy ONeal 指出(内存将在一个堆中分配并在另一个堆中释放).

For some reason, returning a string from a DLL function crashes my program on runtime with the error Unhandled exception at 0x775dfbae in Cranberry Library Tester.exe: Microsoft C++ exception: std::out_of_range at memory location 0x001ef604...

I have verified it's not a problem with the function itself by compiling the DLL code as an .exe and doing a few simple tests in the main function.

Functions with other return types (int, double, etc.) work perfectly.

  • Why does this happen?
  • Is there a way to work around this behavior?

Source code for DLL:

// Library.h
#include <string>

std::string GetGreeting();

.

// Library.cpp
#include "Library.h"

std::string GetGreeting()
{
    return "Hello, world!";
}

Source code for tester:

// Tester.cpp
#include <iostream>
#include <Library.h>

int main()
{
    std::cout << GetGreeting()
}

EDIT: I'm using VS2010.


Conclusion

A workaround is to make sure the library and source are compiled using the same compiler with the same options, etc.

解决方案

Since your error message indicates you're using Microsoft C++ I'll offer an MS specific answer.

As long as you compile both the EXE and the DLL with the SAME compiler, and both link the the SAME version of the runtime DYNAMICALLY then you'll be just fine. For example, using "Multi-threaded DLL" for both.

If you link against the runtime statically, or link against different versions of the runtime then you're SOL for the reasons @Billy ONeal points out (memory will be allocated in one heap and freed in another).

这篇关于从 DLL 函数返回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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