C++严重依赖C样式来导出和导入函数(如果有的话,则不是类/接口(interface)),从而失去了面向对象的风格,这在很多方面使导出的接口(interface)变得晦涩难懂。
可以使用D编程语言以面向对象的方式导出接口(interface)。我可以使用D接口(interface)包装C++(纯)类吗?有哪些可能要考虑的因素?这种方法可行吗?
最佳答案
您可以在D的C++互操作性范围here上找到概述。
面向对象的样式互操作性是通过D的interface
构造提供的:
C++方面
#include<iostream>
class I // Our interface-by-convention
{
public:
virtual void foo() = 0;
void bar() // OK, non-virtual members do not affect binary compatibility
{
/* ... */
}
};
class C : public I
{
private:
int a;
public:
C(int a) : a(a) {}
void foo()
{
std::cout << a << std::endl;
}
};
// This function will be used from the D side
I* createC(int a)
{
return new C(a);
}
D面
extern(C++) interface I
{
void foo();
final void bar() // OK, non-virtual members do not affect binary compatibility
{
/+ ... +/
}
}
// Link `createC` from the C++ side
extern(C++) I createC(int a);
void main()
{
I i = createC(2);
i.foo(); // Write '2' to stdout
}
接口(interface)
extern(C++)
上D的I
导致接口(interface)布局复制带有随附函数C++编译器中的虚函数的单继承C++类的布局。函数声明
createC
上的相同属性使函数在配套的C++编译器中复制等效函数的修改和调用约定。配对编译器对:DMD/DMC++,GDC/g++,LDC/Clang。通过坚持使用虚函数和C ABI进行直接函数调用,通常可以与非配套编译器进行互操作。
请注意,
createC
函数在C++中返回I*
,而在D中仅返回I
。这是因为D接口(interface)和类是隐式引用类型。在更典型的实际使用中,
createC
函数比extern(C)
(然后是C++端的extern(C++)
)更有可能是extern "C"
,以提高编译器之间的互操作性,或在使用DLL时实现更直接的运行时链接。extern(C++)
当前有一些限制;目前无法告诉D extern(C++)
声明位于哪个命名空间中,从而将D限制为只能链接到全局命名空间中的C++符号。关于c++ - D编程: interface at component boundaries,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10083203/