从C调用优雅C ++ [英] Elegantly call C++ from C
问题描述
我们开发的纯 C
(C99)的一些项目。但是,我们在 C ++
一个库源$ C $ CS(数学库)。我们需要这个库,所以我想问一下,什么是该源$ C $ CS?
We develop some project in plain C
(C99). But, we have one library as source codes (math library) in C++
. We need this library so I would like to ask, what is the most elegant way to integrate this source codes?
C
和 C ++
尺寸之比为 20:1
所以移动到 C ++
是不是选项。我们是否应该用静态库? DLL? (这是所有在Windows上)。
Ratio between sizes of C
and C++
is 20:1
so moving to C++
is not the option. Should we use static library? DLL? (It's all on Windows).
推荐答案
编辑:根据在评论的讨论,我要指出的是分离的东西变成一个C兼容结构鸭
和派生类鸭
可能是不必要的。你大概可以放心地铲落实到结构鸭
和消除类鸭
,从而避免实(...)
。但我不知道的C ++不够好(特别是它与C宇宙的交互方式),以提供对这个一个明确的答案。
Based on discussion in the comment, I should point out that separating things into a C-compatible struct duck
and a derived class Duck
is probably unnecessary. You can probably safely shovel the implementation into struct duck
and eliminate class Duck
, thus obviating real(…)
. But I don't know C++ well enough (in particular, the way it interacts with the C universe) to offer a definitive answer on this.
有没有理由,你不能简单地连接所有的C和C ++ code连成一个单一的二进制。
There is no reason you can't simply link all your C and C++ code together into a single binary.
接口到C ++ code要求你包的C ++ API在C API。您可以通过声明一组函数里面的externC这样做{...}编译C ++ code时,没有extern声明编译时
C客户code。例如:
Interfacing to the C++ code requires that you wrap the C++ API in a C API. You can do this by declaring a bunch of functions inside extern "C" { ... }
when compiling the C++ code, and without the extern declaration when compiling the C client code. E.g.:
#ifdef __cplusplus
extern "C" {
#endif
typedef struct duck duck;
duck* new_duck(int feet);
void delete_duck(duck* d);
void duck_quack(duck* d, float volume);
#ifdef __cplusplus
}
#endif
您可以在你的C ++源定义鸭结构,甚至继承了真正的烤鸭
类从它:
You can define the duck struct in your C++ source, and even inherit the real Duck
class from it:
struct duck { };
class Duck : public duck {
public:
Duck(int feet);
~Duck();
void quack(float volume);
};
inline Duck* real(duck* d) { return static_cast<Duck*>(d); }
duck* new_duck(int feet) { return new Duck(feet); }
void delete_duck(duck* d) { delete real(d); }
void duck_quack(duck* d, float volume) { real(d)->quack(volume); }
这篇关于从C调用优雅C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!