COM 互操作:C# COM 类包装器引发异常
我向我的 C# 项目添加了对 COM 类型库的引用。我看到 TlbImp 创建的接口和对象类。其中一个接口方法的签名是:
string GetResString(int hr);
对应于 C++ 标头中定义的非托管对应项:
STDMETHOD(GetResString)(EMS_RESULT hr, /*[out,retval]*/ BSTR *pbszString);
当我使用以下方法调用上述方法时:
ITranslationObject translator = new TranslationObjectClass();
var str = translator.GetResString(2);
我收到一个异常,并显示消息“MfcVSApp1.exe 中 0x00000000 处未处理的异常:0xC0000005:访问冲突”读取位置 0x00000000。”
我尝试使用 P/Invoke 和 DLLImport 手动创建包装器,但得到了同样的结果。
这是我第一次尝试从托管代码进行 COM 互操作,因此我可能遗漏了一些东西。请向我提出任何想法,因为我需要这个工作。
TIA。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
大胆猜测...也许不是 COM 接口问题而是文件路径问题?确保 COM DLL 使用的文件的所有相对路径都相对于 EXE,而不是 DLL。对于 COM,它们并不总是在同一个地方。
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.
例外是有误导性的。实际互操作没有问题。 Tlblmp 关心的实体按预期工作。这个特定的 COM 对象需要在任何其他公开方法之前调用 Initialze 方法,但我没有这样做。初始化 COM 对象后,不再抛出异常并且互操作按预期工作。感谢 Hans P 的提示。
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.