System. runtime. interopservices. gethrforexception trap

Source: Internet
Author: User

Literally, the gethrforexception function is used to obtain the value of the hresult corresponding to the exception. However, gethrforexception will also do one thing: Set the ierrorinfo of the current thread to point to this exception (strictly speaking, it is the ierrorinfo interface pointer in the CCW for exception ). If you are not familiar with ierrorinfo, You can regard ierrorinfo as getlasterror or errno of the com version. Setting ierrorinfo will result in subsequentCodeIf you use geterrorinfo to query the ierrorinfo value, a non-zero result will be obtained, so some code may thinkProgramFailed to continue execution. Worse, if the subsequent code is com InterOP or pinvoke, CLR will check ierrorinfo. If ierrorinfo is not 0, the call fails, and throw an exception or return an error value (depending on whether the preservesigattribute exists ). The direct result is that the function call is successful, but the call fails because ierrorinfo has been set. Interestingly. net has a piece of code for processing resources. This problem happens, and the result indirectly leads to the Brazilian Portuguese version (yes, you are not mistaken J.. net. In fact, I personally think this function should be namedGethrforexceptionandsetierrorinfo(Exception ex); although it is somewhat long, it is clear that it is always better than a short and wrong name.

Under normal circumstances, if you need to obtain the hresult value of exception, you should directly use the exception. hresult attribute. So when should we use gethrforexception? When you write. NET functions are prepared to call unmanaged code (preferably through COM) and return an hresult. In this case, you need to convert the exceptions thrown inside the hosted function to HR, and set the exception information to the ierrorinfo of the current thread. This is the most compliant with the COM specification.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.