C++ DLL 调用在消费应用程序中实现的函数

标签 c++ dll function-pointers virtual-functions

如何从 DLL 函数调用具有复杂返回类型的后实现函数(例如,函数指针或在消费应用程序中实现的虚函数)?

我尝试了以下方案,但出现错误。

测试.h:

#ifdef _DLL_IMPL
#define DLL_EXPORT __declspec(dllexport)  
#else  
#define DLL_EXPORT __declspec(dllimport)  
#endif
typedef string (*test)(void);
extern DLL_EXPORT test __test;
DLL_EXPORT int launch();

测试.cpp:

#define _DLL_IMPL
#include "Test.h"
test __test = 0;
int launch()
{
    string a = __test();
    return 0;
}

消费应用程序是这样的:

主要.cpp:

#include "Test.h"
#pragma comment(lib, "Test.lib")
string test_impl()
{
    string a = "test";
    return a;
}
int main(int args, char** argv)
{
    __test = &test_impl;
    return launch();
}

然后我收到一条后续错误消息:

Windows has triggered a breakpoint in TestRun.exe.

This may be due to a corruption of the heap, which indicates a bug in
TestRun.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while TestRun.exe has focus.

The output window may have more diagnostic information.

我不知道到底发生了什么。当我尝试 char 指针的返回类型时也发生了错误,该指针将在使用 new 运算符的消费应用程序中创建,并将在 DLL 函数中使用 delete[] 运算符释放。

有人可以解释错误发生的原因并建议我解决这个方案吗?谢谢!

最佳答案

在 exe 和 dll 之间传递 C++ 对象确实不是一个好主意,如果对象基于模板类和/或具有内联方法,则更是如此,如果对象在内部分配内存,则更是如此。如果您的应用程序和库之间需要那种接口(interface),那么我建议您将 dll 切换到静态库,这样您就可以避免大多数问题。

如果您需要将dll 保留为dll,那么我建议您只在exe 和dll 之间传递 native 类型。在您的示例中,将 string 的所有用法切换为 char* 可能会解决崩溃问题。

同时采纳 Jim Rhodes 的好建议并声明一个显式的调用约定,即使您发现在这个特定情况下这不是问题所在。

关于C++ DLL 调用在消费应用程序中实现的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7989783/

相关文章:

c++ - 复制特定类时崩溃

c++ - 推荐的 C++ 库设计

c++ - 请解释 "typedef"的语法规则和范围

c++ - 获取指向命名空间中声明的函数的指针

c - 如何在 C 中调用以函数指针作为参数的函数?

c++ - Ruby vs Lua 作为 C++ 的脚本语言

c++ - 如何将运算符作为默认仿函数参数传递?

c++ - 创建 vector 时的默认值,C++

c# - 在C#项目中使用C++ DLL

python - linux下python读写LabView TDMS文件