Using C++ constructors from D -


there page c++ interfacing @ d wiki - https://dlang.org/spec/cpp_interface.html

it says can link c++ code cant link special methods including constructors, destructors , operators overloads because of object's lifetime issues. it's suggested either use wrapper (and construct objects on c/c++ side) or reimplement constructor d. both ways require lot of work done , can impossible. feels huge problem if want use c++ library in d program: example, want use qt's qml , can define needed classes use extern(c++)... stuck constructors , lots of wrappers (like dqml project do) or ported code.

but there way looks working. simple example:

//class.h  class mytestclass {     int x = 0;     int z = 0;  public:     mytestclass(int y);     int getx();     int getz(); };  //class.cpp  #include "class.h"  mytestclass::mytestclass(int y) {     x = y; };  int mytestclass::getx() {     return x; };  int mytestclass::getz() {     return z; }; 

i compile code class.lib link , use later in d program:

//main.d import std.stdio;  extern(c++) {     class mytestclass {         pragma(mangle, "??0mytestclass@@qeaa@h@z") this(int y);         final int getx();         final int getz();     } }  void main() {     int checks = 0;     int goal = 1_000_000_000;     foreach (int i; 0 .. goal) {         mytestclass test = new mytestclass(5);         if (test.getx() == 5 && test.getz() == 0) checks++;     }     writeln(checks, " successfull ", goal);     readln(); } 

this way manually mangle d constructor name c++ 1 because there no way know let compiler itself. create , check objects in loop , watch process memory usage via task manager. every check goes fine (so both z initializer , setting x constructor called properly) , see no memory leak (so looks d creating , destroying objects without problems on billion of iterations).

the question is: there hidden problems calling constructors (and destructors) way? memory issues under more difficult conditions or similar resulting in program crashes? or weird behaviour in cases maybe?

the problem c++ , d constructors , destructors similar things in different order , @ different times.

  • memory initialized before d constructor called. c++ constructor clears memory itself.
  • the c++ destructor called when object goes out of scope. in d garbage collector calls destructor.

this can result in trouble when start mixing class hierarchy between c++ , d.

but in simple case of example (only ctor called, no inheritance mix) there should no problem.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -