Search code examples
c#c++directshowcom-interop

C# COM Interop: How to translate instructions from C++?


I am trying to translate the COM Interop instructions given by my camera manufacturer for C++ to C#.

They write:

To obtain the interface, you use the normal COM functions to ask for the specific interface you need from the capture filter. For example:

IBaseFilter* pSourceFilter;
...
CComQIPtr<IManufacturersInterface> pKs( pSourceFilter );
pKs->SetShutterSpeed( ssAuto1 );

They also give an interface signature and a Guid. The signature looks like

interface IManufacturersInterface: IUnknown
{
    // more stuff
    HRESULT SetShutterSpeed( [in] eShutterSpeed lShutter );
    // more stuff
}

which I translated into C# as

[ComImport]
[Guid("926ddb16-3c8e-476c-9068-eb4555a99231")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IManufacturersInterface
{
    // more stuff
    [PreserveSig]
    int SetShutterSpeed([In] eShutterSpeed lShutter);
    // more stuff
}

From another source I got a similar DirectShow wrapper to access the camera in the first place, including an COM-imported interface IBaseFilter. How would I now translate the first example?

I tried

IManufacturersInterface control = sourceFilter as IManufacturersInterface; // sourceFilter is declared as IBaseFilter
control.SetShutterSpeed(eShutterSpeed.ssAuto1);

but control is null after the cast.

Sorry if I am vague, I have no real clue what I am doing here. This is the first time I had to use COM Interop. It shows, hm? =)


Solution

  • The easiest way to do com interop is to let Visual Studio create the interop for you - I used it with many different com objects and never had any issues with it. To get started, in your C# project select Add Reference and select the tab COM, find the camera manufacturer's object in the list and you should be done. You can now use the com objects as if they were native C#.