Search code examples
c#.netcomcom-interop

COM Interop usage (converting from C++ to C#/.NET)


I have a few COM libraries (TISCOPELib and MIPPARAMLib) that I have been using in C++ (unmanaged) and now I'm converting to C#.

This snippet of code works in C++:

TISCOPELib::IFilterBlockCasette *casette;
... inialization ...
int position = casette->Position;
... other stuff ...

In C#, I would have to do one of the following:

TISCOPELib.IFilterBlockCasette casette = microscope.FilterBlockCasette1; // Init stuff.
MIPPARAMLib.IMipParameter param = casette.Position;
int position = param.RawValue;
... other stuff ...

Or

TISCOPELib.IFilterBlockCasette casette = microscope.FilterBlockCasette1; // Init stuff.
int position = casette._Position;
... other stuff ...

If I did this:

TISCOPELib.IFilterBlockCasette casette = microscope.FilterBlockCasette1; // Init stuff.
int position = casette.Position;
... other stuff ...

I would get the following error:

An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Anonymously Hosted DynamicMethods Assembly

Additional information: Cannot implicitly convert type 'System.__ComObject' to 'int'

The System.__ComObject in this case is supposed to be IMipParameter with int as the RawValue property.

So what is the best course of action here? Use a IMipParameter intermediate step, use _Position, or is there another solution? If I used the IMipParameter, is there a way I can get static type checking?


Solution

  • Try

    int position = (int)casette.Position.RawValue;