2
votes

Please help use ATL COM DLL method in C# application

in ATLLib.idl

...
interface IATLLibMain : IUnknown{
    [helpstring("method hello")] HRESULT hello([out,retval] BSTR* res);
};
...

in ATLLibMain.cpp (ATL SimpleObject Class)

STDMETHODIMP CATLLibMain::hello(BSTR* res)
{
    *res = SysAllocString(L"Hello world!!!");
    return S_OK;
}

I have compiled and registered COM. In C# project, added reference to ATLLib.dll and trying call method like this

IATLLibMain atllib = new ATLLibMainClass();
Console.WriteLine(atllib.hello());

and VS gives error

An unhandled exception of type System.Runtime.InteropServices.COMException occurred in ATLLibTest.exe.

Retrieving the COM class factory for component with CLSID {...} failed due to the following error 80040154.

on line

IATLLibMain atllib = new ATLLibMainClass();

Please show any project sample that use ATL DLL in C# application or help fix this error? Thanks...

1
You get better info about the exception than that. The Message and ErrorCode properties are essential to diagnose the exception. Just paste the message string in the search box and you are very likely to find the answer. - Hans Passant
It's impossible to tell until you also shows us the exact error message of the exception (every exception has Message property) and also stack trace. Maybe you forgot to re-register your COM dll after some changes? - Zdeslav Vojkovic
Retrieving the COM class factory for component with CLSID {...} failed due to the following error 80040154. on line IATLLibMain atllib = new ATLLibMainClass(); - Erik Kianu
The 0x80040154 error (REGDB_E_CLASSNOTREG) tells your ATL DLL has the class in question on type library, but implementation is somehow incorrect: no the interface you quoted, but the whole coclass hosting. You have not yet shown the code on the question, which is wrong. - Roman R.

1 Answers

2
votes

It seems your C# code runs in 64-bit mode, it cannot load 32-bit unmanaged code.

Change Platform Target of the C# application from Any CPU to x86.

Also, register the library using 32-bit version of regsvr32 (see Error Message When You Run Regsvr32.exe on 64-Bit Windows):

%windir%\SysWoW64\regsvr32.exe C:\path\to\library.dll