Search code examples
cclassbisond

Use D class from C code


So, this is what I'm trying to do.

Any ideas how this could be achieved?

Let's say we have this :

class someClass
{
     string someVar;

     this(string v)
     {
          someVar=v;
     }

     void print()
     {
          writeln(someVar);
     }
}

In D, we could do something like :

someClass cl = new someClass("value");
cl.print();

How could we use someClass in C code?


P.S. If you're wondering what I'm trying to do.... I'm currently writing an interpreter in D, using Flex/Bison, so I need a way to interface my D object in the Bison parsing code...


Solution

  • class SomeClass
    {
         string someVar;
    
         this(string v)
         {
              someVar=v;
         }
    
         void print()
         {
              writeln(someVar);
         }
    }
    
    extern(C) void* newSomeClass(char *v) {
        return cast(void*)(new SomeClass(to!string(v))); // \0 terminated
    }
    
    extern(C) void SomeClass_print(SomeClass cls) {
        cls.print();
    }
    

    I think you get the idea, you have to make an extern(C) function for every method of your class. You might be able to automatically generate that code though (pretty straight forward). There are a few more problems GC related, but nothing you can't deal with, but it's kind of a pain.