简体   繁体   中英

COM Interop: C# COM Class Wrapper throws exception

I added a reference to a COM Type Libary to my C# project. I see the interface and object class created by TlbImp. The signature of one of the interface methods is:

string GetResString(int hr);

which corresponds to its unmanaged counterpart defined in the C++ header:

STDMETHOD(GetResString)(EMS_RESULT hr, /*[out,retval]*/ BSTR *pbszString);

When I call the above method using:

 ITranslationObject translator = new TranslationObjectClass();
  var str = translator.GetResString(2);

I get an exception with message "Unhandled exception at 0x00000000 in MfcVSApp1.exe: 0xC0000005: Access violation reading location 0x00000000."

I tried manually creating wrapper using P/Invoke and via DLLImport and got same thing.

This is my first attempt at COM interop from managed code, so I am probably missing something. Please throw any ideas my way as I need this to work.

TIA.

Wild guess... Maybe not a COM interface issue but a file path issue? Make sure all relative paths to files being used by your COM DLL are relative to your EXE, not your DLL. With COM they aren't always in the same place.

Exception is misleading. There is no problem with the actual interop. The entities careted by Tlblmp work as expected. This particular COM object requires an Initialze method to be called beefore any other exposed methods and I was not doing this. After initializing COM object, exception is no longer thrown and interop works as expected. Thanks to Hans P for his tip.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM