Search code examples
c#visual-studio-2010visual-c++comcom-interop

Unable to run a very simple COM client


I'm getting various errors when I try to run a very simple COM client for a very simple COM server that I wrote in C++. The COM server is written in C++ and only has a single method "GetSomeString". I built the ocx of the COM server, registered it using regsrv32, and referenced it from the following C# console application:

using MySimpleActivexControlLib;

namespace SimpleConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var c = new MySimpleActivexControlLib.MySimpleActivexControl();
            c.GetSomeString();
        }
    }
}

When I run the code, I get the following exception:

An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll

Additional information: Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))

I tried to use the component from a C++ console app, and got another error:

... Microsoft C++ exception: _com_error at memory location 0x002bf5e4 ...

The full code can be viewed here. Any help would be highly appreciated.


Solution

  • It certainly depends on what's inside the ActiveX control, but you haven't shown any code of that.

    E.g., the control may require an STA thread to run on and be properly hosted by an ActiveX-friendly container, which is not what your test console application does. Try it from a WinForms application:

    using System;
    using System.Windows.Forms;
    using AxSimpleActiveXControlLib;
    
    class Program
    {
        [STAThread]
        static void Main()
        {
            var c = new AxSimpleActiveXControlLib.AxSimpleActiveXControl();
    
            var form = new Form
            {
                Controls = { c }
            };
    
            form.Load += (s, e) => MessageBox.Show(c.GetSomeNumber().ToString());
    
            Application.Run(form);
        }
    }
    

    This may also help:

    How to create a HelloWorld COM Interop in Visual Studio 2012

    Updated, when you add a reference to an MFC ActiveX control, you should either add it via the Visual Studio WinForms toolbox, or use AxImp.exe tool:

    AxImp.exe SimpleActiveXControl.ocx 
    

    This way, it will generate AxSimpleActiveXControlLib.dll and SimpleActiveXControlLib.dll. The former will contain the System.Windows.Forms.Control-derived wrapper for you ActiveX control. Add both to your project, then try the code I posted above (updated based on the source code you posted).