未在非托管 C++ 中捕获 C# DLL 异常

C# DLL exception not caught in unmanaged C++

作为让自己熟悉通过 COM 在非托管 C++ 中使用 C# DLL 的练习的一部分,我试图了解异常处理的工作原理。我写了一个很小的 ​​C# dll,它只包含一个抛出异常的函数,以及一个调用该函数并尝试捕获异常的 C++ 函数。

这是使用 Visual Studio 2012 用 C# 编写的 DLL:

namespace ExceptionThrowingLib
{
    public interface IExceptionThrower
    {
        void ThrowException();
    }

    public class ExceptionThrower : IExceptionThrower
    {
        public ExceptionThrower() { }
        public void ThrowException()
        {
            using (StreamWriter writer = new StreamWriter("c:/misc/exceptionthrower.txt", true))
            {
                writer.WriteLine("Exception generation request received at " + DateTime.Now.ToString());
            }
            throw new Exception("This is a requested exception.");
            using (StreamWriter writer = new StreamWriter("c:/misc/exceptionthrower.txt", true))
            {
                writer.WriteLine("This should never appear in the output file.");
            }
        }
    }
}

下面是尝试使用它的函数,使用 Visual Studio 2008 用 C++ 编写:

void HandleException()
{   
    IExceptionThrowerPtr pThrower(__uuidof(ExceptionThrower));
    try
    {
        pThrower->ThrowException();
        AfxMessageBox(_T("No exception caught."));
    }
    catch (...)
    {
        AfxMessageBox(_T("I caught an exception!"));
    }
}

当我调用这个函数时,"No exception caught" 消息出现。

我希望客户端 (C++) 端能够捕获 _com_error 对象并适当地处理它以了解发生了什么,但似乎没有捕获到任何东西。为什么不?我做错了什么吗?

谢谢。

你不是真的做错了什么,而是理解错了

C++ 代码未捕获异常,因为没有向 C++ 代码抛出异常。 .NET 运行时中的 CLR/interop 层在异常传回之前捕获异常。所有良好的 COM 代码都不会从 COM 方法或 属性 中抛出异常,但 return 是失败代码。

ThrowException() 的 return 代码 (HRESULT) 是什么。它不应该是 S_OK 但可能是 E_FAIL 或其他一些描述性错误。

您是否使用 #import 生成了 _com_ptr 实现?

如果是这样,请注意省略 raw_interfaces_only 指令,因为它会抑制错误处理包装函数的生成。