A question about C++ interop

Jacob Carlborg doob at me.com
Sat Mar 28 07:33:38 UTC 2020


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();

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list