D: interface at component boundaries

C ++ relies heavily on the C style for exporting and importing functions (rather than classes / interfaces, if any), thus losing the object-oriented taste, which makes the export interface cryptic in many ways.

The DD programming language can be used to export interfaces in an object-oriented style. Can I wrap C ++ (pure) classes using D interfaces? What are the possible elements to consider? This approach is possible.

+6
source share
1 answer

You can find an overview on the spectrum of D C ++ interaction here .

Object-oriented style functionality is provided through the D interface construct:

C ++ side

 #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 side

 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 extern(C++) on interface I forces the layout of the interface to replicate the layout of the class with a single C ++ inheritance using virtual functions in the C ++ compiler.

The same attribute in the createC function createC forces the function to replicate the convention of switching and calling the equivalent function in the C ++ compiler.

Companion compiler parts: DMD / DMC ++, GDC / g ++, LDC / Clang. It is often possible to interact with a non-companion compiler using virtual functions and C ABI for direct function calls.

Note that the createC function returns I* in C ++ and just I in D. This is because D interfaces and classes are implicit reference types.

In more typical real-time mode, the createC function is more likely to be extern(C) than extern(C++) (and then extern "C" on the C ++ side), for greater compatibility between compilers or more believable, direct linking of runtime when using dll.

extern(C++) currently has some limitations; it is currently not possible to tell D, which contains an extern(C++) declaration space, restricting D to only the ability to refer to C ++ characters in the global namespace.

+5
source

Source: https://habr.com/ru/post/912812/


All Articles