Interfacing with XPCOM

John Reimer terminal.node at gmail.com
Sat Dec 6 23:04:22 PST 2008


Hello Jason,

> Sergey Gromov wrote:
> 
>> But what's the typical use case for extern(C++) objects ?  I think
>> it's something like this:
>> 
>> extern(C++) class CppInterfaceClass { ... }
>> 
>> extern(C++) CppInterfaceClass create()
>> {
>> return new CppInterfaceClass(...);
>> }
>> extern(C++) void destroy(CppInterfaceClass obj)
>> {
>> delete obj;
>> }
> while extern(C++) will accept that code, but it won't work right.
> 


(Sorry, I've been away for a bit)

I don't think the example is how extern(C++) was designed to work either.

When used for C++ classes, extern(C++), from what I gather, is intended to 
be applied to an /interface/ in the D code, NOT a D class:

extern(C++) interface Foo { 
    int foo(int a, b);
}

This interface represents the link to the external C++ class.  An instance 
of that class is created by the C++ code using a factory function which D 
links to in its code (BUT does not implement):

extern(C++) Foo create();            // in C++ code this is something like 
Foo* create() { return new Foo; }
extern(C++) void destroy(Foo F);  // also in C++ code since the same should 
destroy it

In the D code, the factory function enforces the stricture that the C++ code 
is responsible for it's own object creation and destruction.  D code should 
touch this.  About the only thing that the D gc might monitor is the D interface 
reference created.

Assignment to the extern(C++) interface in D like so:

Foo F = create();

ensures that we have access to the C++ object.  Perhaps a scope() statement 
may be used to call the C++ destroy method.

Of course, the documentation on extern(C++) already discusses this.  I just 
thought it should be made clear here since the prior code sample implies 
that the C++ object creation and destruction are done in D, which it cannot 
be.

The fact that D 2.0 uses a special-case of D interface (kind of similar to 
COM interfaces) was primarily why I became interested in the possibility 
of using it as an opportunity to interface with XPCOM.  But it seems XPCOM 
is more appropriatly implemented by taking advantage of the COM alias functionality 
as is.

Also the extern(C++) technique is a D 2.0-only feature, so I will leave such 
experimentation for the such a time as DWT/XPCOM is ready to be ported to 
D 2.0.

-JJR





More information about the Digitalmars-d mailing list