C++ interface vs D and com

Adam Sansier via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 12 15:44:56 PDT 2016


On Tuesday, 12 July 2016 at 22:01:41 UTC, Lodovico Giaretta wrote:
> On Tuesday, 12 July 2016 at 21:21:04 UTC, Adam Sansier wrote:
>> On Tuesday, 12 July 2016 at 15:12:21 UTC, Lodovico Giaretta 
>> wrote:
>>>
>>> I'm not an expert in this field, but did you read this[1]?
>>>
>>> [1] https://dlang.org/spec/interface.html#com-interfaces
>>
>> Yes, of course...
>
> Well, I asked because you say you marked your interfaces as 
> extern(C++), which is *not* what the spec says you should do.
> Of course, because you didn't give us much infos on what's not 
> working, we have to guess and point you to some generic 
> resources.
> Did you read the wiki entry[1], and had a look to some source 
> code[2]? It may be useful to understand if it's a simple 
> mistake on your side or some more deep issue.
>
> [1] https://wiki.dlang.org/COM_Programming
> [2] 
> https://github.com/dlang/druntime/blob/master/src/core/sys/windows/com.d

I've spent the last 2 days working on it looking up as much as I 
can. It's not as if there is any sensible information on it. 
Trust me... If you haven't done much with it, there is no way you 
can imagine how convoluted it is... you can pretend, but that 
doesn't do it justice.

Ok, I got it to work but had to completely hack it. This is not 
the way to go about it though! There must be a better way!

1. Change the interface in to a class, create dummy functions for 
all members. This is because we must be able to instantiate the 
interface so we can modify it's vtable ptr. With just the 
interface, we'll never be able to create the object(maybe malloc 
will do?) Abstract class won't work either for similar reasons.

The layout must look exactly like the interface(in order and 
include IUnknown methods).

2. change __vtbl ptr:

auto interfaceClass = new InterfaceClass();
interfaceClass.__vptr = cast(immutable(void*)*)(*ptr);

where ptr is what is returned from CoCreateInstance(if it is a 
direct object).

Essentially we are creating a template with InterfaceClass then 
swapping it's vtable with the correct one. We technically don't 
need to recreate the class exactly but it's required for 
intellisense and compiler semantics. We could use opDispatch, etc.

The vtable modification isn't bad, though. That's just a one 
liner.



So, the problem now, is how to take the interface, which is 
simple, no implementation, and either create the implementation 
or create a sort of simple empty proxy that can be used to 
instantiate the interface?

Basically the problem now is, that using this method one has to 
create a class and add stubs for all the methods along with all 
the inherited methods. This is tedious and they serve no purpose.





More information about the Digitalmars-d-learn mailing list