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
}
D 在接口(interface) I
上的 extern(C++)
导致接口(interface)布局在配套的 C++ 编译器中复制具有虚函数的单继承 C++ 类的布局。
函数声明 createC
上的相同属性导致函数复制配套 C++ 编译器中等效函数的修饰和调用约定。
配套编译器对:DMD/DMC++、GDC/g++、LDC/Clang。通过坚持使用虚拟函数和用于直接函数调用的 C ABI,通常可以与非配套编译器进行互操作。
请注意,createC
函数在 C++ 中返回 I*
而在 D 中仅返回 I
。这是因为 D 接口(interface)和类是隐式引用类型。
在更典型的现实世界中,createC
函数更可能是 extern(C)
而不是 extern(C++)
(然后是 C++ 端的 extern "C"
),以提高编译器之间的互操作性,或在使用 DLL 时更直接的运行时链接。
extern(C++)
目前有一些限制;目前无法告诉 D extern(C++)
声明在哪个命名空间中,将 D 限制为只能链接到全局命名空间中的 C++ 符号。
关于c++ - D编程: interface at component boundaries,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10083203/