Interfacing with XPCOM
Sergey Gromov
snake.scaly at gmail.com
Mon Dec 8 01:23:02 PST 2008
Sun, 7 Dec 2008 07:04:22 +0000 (UTC), John Reimer wrote:
> 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):
This is one possible use. But the opposite use is also perfectly
possible. The ultimate example of the opposite use is a COM object
implemented in D.
> 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.
Of course it can. My example wasn't quite correct though. Assuming
your definition of interface Foo, here is the implementation:
> extern(C++) interface Foo {
> int foo(int a, int b);
> }
class FooImpl : Foo {
override int foo(int a, int b) { // implicit extern(C++), correct VTAB placement
return a + b;
}
}
extern(C++) Foo createFoo() {
return new FooImpl;
}
extern(C++) void destroyFoo(Foo foo) {
delete foo;
}
The only problem with this code is that FooImpl will be GCed as soon as
it leaves the createFoo().
More information about the Digitalmars-d
mailing list