Ctypes 捕获异常

Ctypes catching exception

本文关键字:捕获异常 Ctypes      更新时间:2023-10-16

我正在玩ctypes和C/C++ DLL我有一个非常简单的"数学"dll

double Divide(double a, double b)
{
    if (b == 0)
    {
       throw new invalid_argument("b cannot be zero!");
    }
    return a / b;
}

到目前为止它有效唯一的问题是,我在 Python 中收到 WindowsError 异常,并且无法检索文本b 不能为零我必须抛出一些特殊的异常类型吗?还是必须更改 Python 代码?蟒蛇代码:

from ctypes import *
mathdll=cdll.MathFuncsDll
divide = mathdll.Divide
divide.restype = c_double
divide.argtypes = [c_double, c_double]
try:
    print divide (10,0)
except WindowsError:
    print "lalal"
except:
    print "dada"

浏览 Python 2.7.3 的 ctypes 文档,我看不到任何对C++的引用,也看不到通过 ctypes 调用C++代码中抛出异常。似乎 ctypes 仅用于调用 C 函数,不处理C++异常。

试试这个:

from ctypes import *
mathdll=cdll.MathFuncsDll
divide = mathdll.Divide
divide.restype = c_double
divide.argtypes = [c_double, c_double]
try:
    print divide (10,0)
except WindowsError as we:
    print we.args[0]
except:
    print "Unhandled Exception"