gpt4 book ai didi

c++ - 我可以像这样混合使用 pimpl 和 C 接口(interface)吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:25:34 27 4
gpt4 key购买 nike

我想保持我的dll的向后兼容性,虽然Pimpl模式涉及到必须导出整个类,所以名称重整导致不同的编译器无法支持,在这种情况下,我可以提供C兼容接口(interface)吗一起喜欢跟随?

在公共(public)头中:

#ifdef CPPDYNAMICLINKLIBRARY_EXPORTS
# define SYMBOL_DECLSPEC __declspec(dllexport)
# define SYMBOL_DEF
#else
# define SYMBOL_DECLSPEC __declspec(dllimport)
# define SYMBOL_DEF __declspec(dllimport)
#endif

#ifdef _WIN32
#define GRAPHICAPI __stdcall
#else
#define GRAPHICAPI
#endif

#ifdef __cplusplus
#define EXTERN_C extern "C"
#else
#define EXTERN_C
#endif // __cplusplus

#ifdef __cplusplus
namespace myapi{
struct SYMBOL_DECLSPEC Graphics{
Graphics();
~Graphics();
void drawLine(int,int,int,int);
void drawLine(Point,Point);
private:
struct Impl;
const Impl* impl;
}
}//end of myapi
#endif // __cplusplus

struct Graphics;
typedef struct Graphics *PGraphics;

#ifdef __cplusplus
extern "C" {
#endif
SYMBOL_DEF PGraphics GRAPHICAPI newGraphics();
SYMBOL_DEF void GRAPHICAPI deleteGraphics(PGraphics);
SYMBOL_DEF int GRAPHICAPI Graphics_drawLine4(PGraphics,int,int,int,int);
SYMBOL_DEF int GRAPHICAPI Graphics_drawLine2(PGraphics,Point,Point);
#ifdef __cplusplus
}
#endif

同样在dll项目中,def文件有如下定义:

exports
newGraphics @1
deleteGraphics @2
Graphics_drawLine4 @3
Graphics_drawLine2 @4

如果你在def文件中没有指定序数,当你添加新函数如Graphics_drawArc时,Graphics_drawArc函数会在Graphics_drawLine4之前导出,旧的应用程序调用Graphics_drawLine4实际上调用了Graphics_drawArc,导致崩溃。

上述解决方案是否正确?

最佳答案

如果您将其移植到没有__stdcall 概念的不同平台,我会将调用约定隐藏在宏后面:

#ifdef _WIN32
#define GRAPHICAPI __stdcall
#else
#define GRAPHICAPI
#endif

SYMBOL_DEF PGraphics GRAPHICAPI newGraphics();
SYMBOL_DEF void GRAPHICAPI deleteGraphics(PGraphics);
SYMBOL_DEF int GRAPHICAPI Graphics_drawLine4(PGraphics,int,int,int,int);
SYMBOL_DEF int GRAPHICAPI Graphics_drawLine2(PGraphics,Point,Point);

除此之外,我没有发现任何问题。不同 C++ 编译器之间的任何 ABI 差异都隐藏在具有相当稳定的 ABI 的 C 接口(interface)之后。

关于c++ - 我可以像这样混合使用 pimpl 和 C 接口(interface)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19804703/

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