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

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

问题描述

由于某种原因,从DLL函数返回一个字符串会在运行时崩溃我的程序错误 Cranberry Library Tester.exe中的0x775dfbae处理异常异常:Microsoft C ++异常:std :: out_of_range在内存位置0x001ef604 ..



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



其他返回类型( int double 等)工作完美。




  • 为什么会这样?

  • 有没有办法解决这个问题?



DLL的源代码:

  // Library.h 
#包括< string>

std :: string GetGreeting();

  // Library.cpp 
#includeLibrary.h

std :: string GetGreeting()
{
返回你好,世界! ;
}

测试者的源代码:

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

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

编辑:我在使用VS2010。






结论



解决方法是确保使用相同的编译器相同的选项等。

解决方案

您的错误消息表示您正在使用Microsoft C ++,我将提供MS具体的答案。



只要使用SAME编译器编译EXE和DLL,并且都链接了SAME版本的运行时间DYNAMICALLY,那么你会很好。例如,对于两者都使用多线程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天全站免登陆