DLLs with COM interface
Mike
vertex at gmx.at
Thu Dec 6 08:57:58 PST 2007
On Wed, 05 Dec 2007 12:15:10 +0100, Henrik <zodiachus at gmail.com> wrote:
> Hello!
>
>
> I was reading up on http://www.digitalmars.com/d/dll.html#com regarding
> how to call DLLs with a COM interface, since this is exactly what I am
> struggling with.
>
> I'm trying to interface with proprietary DLLs that I know expose COM
> interfaces. Fortunately, I have the documentation for them so I know
> exactly what methods they expose.
>
> There is, for example trtCom.dll, which exposes a trtComMgr class, which
> has a method AboutBox(). I thought I'd start with calling that, since
> it takes no arguments and returns nothing.
>
> Now, it said in the article mentioned above that COM objects and D
> interfaces are virtually the same thing, so I tried this:
>
> extern(Windows)
> {
> interface MbtComMgr
> {
> void AboutBox();
>
> }
> }
>
> But that wasn't very popular with the D compiler. It simply said:
> Error: need 'this' to access member AboutBox
>
> What would be the proper way of accessing a COM DLL?
An interface on its own is just a contract saying how the actual instance
will be layed out in memory and how it will be called (usually extern
(Windows) for COM). You need an actual instance, which you can get from
Windows with the CoCreateInstance call:
extern (Windows) IFooBar : IUnknown
{
...
}
CoInitialize(null); // initialize COM before getting the
instance
scope (exit) CoUninitialize(); // close COM after we're finished
IFooBar instance; // this just declares a reference to the interface
IFooBar which is null at first
CLSID clsid = ...; // you need to know the DLL's class id first!
CLSCTX clsctx = ...; // the context, normally CLSCTX_INPROC_SERVER
auto rc = CoCreateInstance(clsid, null, clsctx, clsid,
cast(void**)&instance);
if (rc != S_OK) throw new Exception("Couldn't create instance!");
/* now you can call the IFooBar instance */
instance.Release(); // release the instance
The important part is to get the instance pointer from COM with
CoCreateInstance. It creates the instance and stores the pointer to it in
instance (that's why there's a cast(void**) in there). Deriving from
IUnknown is important too 'cause then the housekeeping is done
automatically and you just use the instance as if you'd created it with
new. Don't forget to release the instance after you're done with it, don't
delete it!
The definitions for CLSID etc. are in phobos and Tango, just search for
them. If it doesn't work (like it did for me) I can recommend downloading
the schooner project from dsource.org and using its win32 files - they
have every definition and they work.
-Mike
--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
More information about the Digitalmars-d-learn
mailing list