Search code examples
c#com

C# unable to see or use a COM object's methods


After reading endless questions on accessing a COM object from C#, nothing seems to have addressed my issue. I've created a COM object in C++ and registered it successfully. OLEView can see and create an instance of my object. I'm also able to create an instance of it and invoke it's methods with a simple separate C++ application.

In C#, I've added the DLL in the Reference Manager -> COM -> Type Libraries, and appear to be able to create an instance of the object (named Coffee):

System.Guid g = new System.Guid("D857715A-BEB9-4436-BBB7-1143F651196C");
Type myType = Type.GetTypeFromCLSID(g);
dynamic obj = Activator.CreateInstance(myType);
Coffee xx = (Coffee)obj;

The GUID represents the coclass in my .idl for the COM object:

...
[
    uuid(D857715A-BEB9-4436-BBB7-1143F651196C)      
]
coclass Coffee
{
    [default] interface ICoffee;
    [default, source] dispinterface _ICoffeeEvents;
};

This object contains a member variable 'ounces', a get_ and put_, and a method named TestMethod that does nothing except return S_OK. All can be invoked from C++. In C#, intellisense sees nothing except 'int ICoffee.Ounces' for the object. get_ and put_ do not show up, nor does TestMethod.

I've also tried Type.GetMethod("TestMethod") and invoking on that, but MethidInfo ends up null:

MethodInfo testMethod = myType.GetMethod("TestMethod");
object value = testMethod.Invoke(obj, new object[] { });

Also tried invoking it on the dynamic object:

obj.TestMethod();

Additional information: 'System.__ComObject' does not contain a definition for 'TestMethod'

What exactly am I missing that's not letting C# entirely use the object?

Edit: ICoffee in .idl:

[
  object,
  uuid(35B4618D-733B-453D-9714-FFCB35740FB2),
  dual,
  nonextensible,
  pointer_default(unique)
]
interface ICoffee : IDispatch{

  [propget, id(1)] HRESULT Ounces([out, retval] LONG* pVal);
  [propput, id(1)] HRESULT Ounces([in] LONG newVal);
  [id(2)] HRESULT GetOunces([in] LONG* nOunces);
  [id(3), helpstring("This is a test method")] HRESULT TestMethod();
};

Solution

  • Well, I started from scratch on my two test projects, and this time (using early-bound access) I was able to access my methods. Not sure what was wrong.. but this is resolved.