Calling D from C++

Loopback elliott.darfink at gmail.com
Tue Jul 19 03:39:18 PDT 2011


On 2011-07-19 05:46, Johann MacDonagh wrote:
>>
>> What is the best method to accomplish this, and are there any
>> limitations with this method (do I have to allocate the class with
>> malloc instead etc.)?
>
> Your C++ class "Base" is not compatible with your D "Foo" class. The
> v-tables are not guaranteed to be identical. I'm not even sure if D's
> thiscall is the same as C++'s thiscall. It's just not going to work.
> Most languages don't support this. This is why we use C bindings.
> Everyone supports C ;)
>
> Now, you can do something like this:
>
> struct Foo
> {
> int x;
> float y;
> }
>
> extern(C) void* GetNewFoo()
> {
> // Note: Don't use new here otherwise the GC may clean it up
> return cast(void*) core.memory.GC.malloc(Foo.sizeof);
> }
>
> extern(C) float Foo_DoSomething(Foo* foo)
> {
> return foo.x + foo.y;
> }
>
> extern(C) void FreeFoo(Foo* foo)
> {
> core.memory.GC.free(foo);
> }
>
> I haven't tried this, but something like this should work. Structs are
> inherently compatible between languages. Of course, you won't be able to
> do any kind of polymorphism.
>
> Does this help?

Very interesting!

This might help depends; are you able to have structures with functions?
Are they still analogous if you implement them?

Also, how come the class-interface inheritance didn't work to
communicate with C++. Is the "Interface to C++" doc's outdated?

"Calling D Virtual Functions From C++"

http://www.digitalmars.com/d/2.0/cpp_interface.html


More information about the Digitalmars-d-learn mailing list