COM`HRESULT`被包装成在.NET中的异常 [英] COM `HRESULT` is wrapped into an Exception in .NET
问题描述
(preliminary注:我还没有完全达到速度与整个互操作的事情...)
(preliminary note: I'm not yet fully up to speed with the whole 'interop' thing...)
当从在.NET中使用COM库,所有的 HRESULT
方法将被包装成的东西,抛出当返回code未成功了。
When using a COM library from within .NET, all HRESULT
methods are wrapped into something that throws when the return code is not SUCCEEDED.
//ATL magic exluded
class C {
HRESULT foo(){ return E_FAIL; }
};
// usage code:
if( SUCCEEDED( c.foo() ) ) {
// success code
} else {
// failure code
}
这code的.NET版本内容如下:
The .NET counterpart of this code reads:
try {
c.foo();
// success code
} catch ( Exception e ) {
// failure code
}
有没有办法直接访问COM返回code在.NET中,所以没有异常处理是必要的?
Is there a way to access the COM return code directly in .NET, so that no exception handling is needed?
推荐答案
是的,但你必须手动定义的互操作接口(而不是使用tlbimp.exe是),并使用<一个href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.$p$pservesigattribute.aspx"相对=nofollow> preserveSig 所讨论的方法的属性。
Yes, but you'll have to manually define the interop interface (rather than use tlbimp.exe) and use the PreserveSig attribute on the methods in question.
例如:
[ComImport]
[Guid("your-guid-here")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMyComInterface
{
[PreserveSig]
int DoSomething(out int result);
}
这是一个COM方法的签名相当于 HRESULT DoSomething的([出来,RETVAL] INT *结果);
That is the equivalent of a COM method with the signature HRESULT DoSomething([out, retval] int *result);
如果您的接口是非常复杂的,或你停留在如何定义互操作界面,我建议使用tlbimp.exe是,然后使用反射或ILSpy或类似的反编译生成的接口的东西,然后编辑者根据自己的喜好。保存工作,太。 :)
If your interface is very complicated or you get stuck on how to define the interop interface, I recommend using tlbimp.exe, then using Reflector or ILSpy or something similar to decompile the generated interfaces, and then edit those to your liking. Saves work, too. :)
这篇关于COM`HRESULT`被包装成在.NET中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!