flakes
flakes

Reputation: 23674

Understanding COM Objects and how to declare them

Say I want to create the interface for IMMDeviceEnumerator.

I see examples online showing the definition:

[ComImport]
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMMDeviceEnumerator
{

}

What I understand (maybe): The [ComImport] Attribute specifies that it's from a dll. The [Guid] attribute is the interface identifier.

What I don't understand: How was this GUID value obtained? What does the [InterfaceType] attribute do? How do I fill in the rest of the functions?

I'm so lost trying to figure this stuff out, all the documentation is super opaque.

Upvotes: 3

Views: 1184

Answers (2)

Seth Kitchen
Seth Kitchen

Reputation: 1566

You create the GUID yourself. There are generators online if you don't want to assign one yourself.

All interface types should derive from IUnknown.

Update: here is a generator. https://www.guidgenerator.com/online-guid-generator.aspx

They use the same one because IMMDeviceEnumerator has already been defined with that specific GUID. If you create your own interface, you will create your own GUID.

You derive off IUnknown because

"Within that constraint, your custom interface can support almost any method or parameter, including asynchronous methods. You can also generate a type library for your custom interfaces so that clients can access information about your object's methods at run time. "

Upvotes: 0

Mark Brackett
Mark Brackett

Reputation: 85665

How was this GUID value obtained?

The GUID is created as part of the COM interface definition; since you're trying to call someone else's object - you need to use their GUID. You can find it in the mmdeviceapi.h the MMDevice docs point to.

Header file Mmdeviceapi.h defines the interfaces in the MMDevice API.

 MIDL_INTERFACE("A95664D2-9614-4F35-A746-DE8DB63617E6")
    IMMDeviceEnumerator : public IUnknown

The normal way to do this is to add a reference to the COM dll or run tlbimp.exe which will generate a COM Class Wrapper for you with all the magic goo.

If a COM type library isn't available, though - then you basically have to do it yourself by going through the IDL file.

Like p/invoke signatures, this can get pretty painful - so best to use an existing one if you can.

For the larger questions of COM interop, it basically requires learning a little bit of COM and being familiar with C#. The general docs are out there, but usually if you're just trying to use a well known COM component you're best off using a library if you can.

Upvotes: 2

Related Questions