A question about C++ interop

YD diyu60607 at yahoo.com
Sat Mar 28 19:14:38 UTC 2020


On Saturday, 28 March 2020 at 07:33:38 UTC, Jacob Carlborg wrote:
> On 2020-03-27 20:17, YD wrote:
>> Hi, I have a C++ header file which looks like
>> 
>>      class A {
>>      public:
>>          static A *create();
>>          virtual int f() const = 0;
>>      };
>> 
>> And there is a C++ library file which provides the 
>> implementation, so that if I write a C++ program and call
>> 
>>      auto *p = A::create();
>>      std::cout << p->f() << '\n';
>> 
>> It will work.
>> 
>> Now I want to interface to this C++ library through D, and I 
>> wrote
>> 
>>      module test;
>> 
>>      import std.stdio;
>> 
>>      extern(C++) {
>>          class A {
>>                  static A *create();
>>                  abstract int f() const;
>>          }
>>      }
>> 
>>      void main() {
>>          auto p = A.create();
>>          writeln(p.f());
>>      }
>> 
>> This program will compile and link, but it core dumps at the 
>> call to f().
>> 
>> If I wrap up the C++ interface into a C interface (using a 
>> void *), and interface to the wrapped-up C library through D, 
>> it will work fine.
>> 
>> So what am I doing wrong here? Thanks!
>
> Classes in D are always passed by reference. Try dropping the 
> pointer in the `create` method:
>
> static A create();

Hi, now I have a further question: when the C++ class A actually 
has a method that looks like

     virtual void get_info(std::string &s) const = 0;

in order to preserve the virtual function table layout (I found 
that if I omit this function completely in the D declaration, and 
try to use a virtual member function originally defined in C++ 
after this function, the result is core dump), even if I don't 
use this function, in the D file I have to put in line like this

     abstract void get_info(basic_string!(char) s) const;

When I try this on Linux (Ubuntu 18.04), the compiler (both dmd 
and ldc2) will complain about "std::__cxx11::basic_string is not 
yet supported", but otherwise the code compiles and links 
correctly, and can run without problem.

But when I try this on Windows 10, dmd will simply refuse to 
compile it, saying "windows c++ runtime not supported", and ldc2 
will allow the compilation but fail at the linking stage, saying 
something like

     "error LNK2019: unresolved external symbol 
__D4core6stdcpp9allocator33_Allocate_manually_vector_alignedFNixkZPv referenced in function __D4core6stdcpp9allocator__TQnTaZQs8allocateMFNikZPa"

So does this mean that there is no way I can interface to this 
C++ API in Windows? Thanks.





More information about the Digitalmars-d-learn mailing list