gpt4 book ai didi

windows - 我可以在单个 DLL header 中混合使用 C 和 C++ 导出吗?

转载 作者:可可西里 更新时间:2023-11-01 10:00:04 26 4
gpt4 key购买 nike

在这里帮助我,因为我一半相信我不能做我想做的事,一半相信应该有一个合适的解决方法。

我有一个用 C++ 实现的 DLL,因此将一些类导出到链接到它的其他 C++ 模块。没关系。现在我想从 C 模块(另一个 DLL)链接到这个 DLL,所以我将提供一个“扁平化”C 接口(interface)并在内部处理 C++ 内容。这也很好。

问题是我想将其作为单个 .h 和关联的 .lib 提供给 C 或 C++ 客户端。所以我的 DLL 中有类似于以下内容的内容:

#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif

// export a class for the C++ clients
class DLL_API CExportedClass
{
public:
CExportedClass();
// etc. etc.
};

// export flattened C interface for non-C++ clients
#ifdef __cplusplus
extern "C" {
#endif

DLL_API void DoSomethingInternally(); // i.e. implementation uses CExportedClass

#ifdef __cplusplus
}
#endif

当然,这在导入到 C++ 模块时工作正常,但在导入到 C 模块时无法编译,因为它无法识别 class 声明。

所以我认为我什至可以做到这一点是错误的吗?我需要分成两个标题吗?在 class 声明(或其他类型的 #ifdef)周围使用 #ifdef __cplusplus 是否正确且可接受?

真的在努力寻找一个“干净”的答案。

最佳答案

MSDN 上有几篇关于混合 C 和 C++ 的文章:

我认为您可以简单地看一下 windows.h 或类似的头文件,它们在 C 和 C++ 上都可以正常工作,没有任何问题。

基本上它是这样工作的:

在头文件的最开始

#ifndef _MYHEADER__H
#define _MYHEADER__H

#ifdef __cplusplus
extern "C" {
#endif

//Decalrations
//........
//........


//Bottom of your header

#ifdef __cplusplus
}
#endif
#endif

所以你的标题应该是这样的:

#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif

#ifdef __cplusplus
//This part of header is not visible for ANSI C compiler
// export a class for the C++ clients
class DLL_API CExportedClass
{
public:
CExportedClass();
// etc. etc.
};
#endif


#ifdef __cplusplus
extern "C" {
#endif


DLL_API void DoSomethingInternally(); // i.e. implementation uses CExportedClass

#ifdef __cplusplus
}
#endif

这是它寻找 ANSI C 编译器的方式:

#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif
DLL_API void DoSomethingInternally();

这是 C++ 编译器的查找方式:

#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif

class DLL_API CExportedClass
{
public:
CExportedClass();
// etc. etc.
};
extern "C" {

DLL_API void DoSomethingInternally();

}

但是,您在 header 中声明了类,因此 C 编译器不会对此感到满意,您应该将它放在“C”声明之外。

看这里:

http://www.parashift.com/c++-faq/mixing-c-and-cpp.html

关于windows - 我可以在单个 DLL header 中混合使用 C 和 C++ 导出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15829259/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com