Connecting with C++

This book devoted an entire chapter to connecting D and C, yet there's only this small section here in the last chapter to discuss interfacing with C++. The reason is that this feature of D is, as I write, under active development. Interfacing with C is rather easy, as most C compilers conform to well-defined, standard ABIs. The story is different with C++, where there is no standard ABI. This is particularly an issue when it comes to name-mangling, where compilers have traditionally followed their own schemes. Additionally, there is no such one-to-one correspondence between C++-specific features and D features as there is when C is compared with D. There are also key differences in the languages to consider. For example, C++ supports multiple inheritance, D does not; classes in C++ are value types, while D classes are reference types; D const is transitive, C++ const is not; and so on. Most of these issues as yet have no solutions.

Despite all the caveats, there is a significant amount of interoperability between the two languages. There is much common ground in their shared compatibility with C. Additionally, progress has been made on interacting with several C++-specific features. It all starts with the linkage attribute extern(C++). This is important in getting the name-mangling correct and is highly dependent on the linker being used. Libraries generated with the Microsoft tools, whether they are static or dynamic, will have different name-mangling than those generated by the Digital Mars C++ compiler (DMC) or with GCC.

Namespaces are neatly handled as an extension to the linkage attribute. Consider the following C++ declaration:

namespace mylib {
  void MyFunction(int a);
}

This can be directly translated to D as:

extern(C++, mylib) {
  void MyFunction(int a);
}

A C++ struct, when used as a POD type with no inheritance, can be translated directly to a D struct. It's also possible to translate some C++ aggregate types directly to D classes or interfaces, though things get complicated when templates or multiple inheritance are involved.

If you are interested in pursuing D and C++ interoperability, a great place to begin is with a presentation Walter Bright gave at a meeting of the Northwest C++ Users' Group, titled Interfacing D to Legacy C++ Code. A video of the talk can be found on YouTube at https://www.youtube.com/watch?v=IkwaV6k6BmM. Alternatively, there is a fork of LDC called Calypso that takes a different approach to getting the two languages to work together. You can find it at https://github.com/Syniurge/Calypso. There are a few members of the D community taking the time to explore this topic, so more current information can usually be found in the #D IRC channel or the D forums.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.103.154