Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 550
flakes Avatar asked Oct 24 '25 17:10

flakes


1 Answers

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.

like image 177
Mark Brackett Avatar answered Oct 26 '25 07:10

Mark Brackett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!