Ctypes捕获异常 [英] Ctypes catching exception

查看:201
本文介绍了Ctypes捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  double Divide(double a,double b)
{
if(b == 0)
{
throw new invalid_argument(b can not be zero! ;
}

返回a / b;
}

它工作到目前为止
唯一的问题,我得到一个WindowsError Python中的异常和我无法检索文本
b不能为零
是否有一些特殊的异常类型必须抛出?还是必须修改Python代码?
python代码:

 来自ctypes import * 

mathdll = cdll.MathFuncsDll
divide = mathdll.Divide
divide.restype = c_double
divide.argtypes = [c_double,c_double]

try:
print divide(10,0)
除了WindowsError:
printlalal
except:
printdada

$ b b

解决方案

首先,你不应该在C ++中使用异常规范。这是C ++的一个可怕的特性,它已在最新标准中被弃用。另外,语法 throw(...)根本不是有效的C ++,这行不使用像gcc这样的标准编译器编译:

  double Divide(double a,double b)throw(...)

我认为你依赖于一个非标准的Visual C ++扩展,据我所知,这是无用的,因为Visual C ++忽略所有的异常规范,除非 throw()没有参数。



通过Python 2.7.3的ctypes文档我看不到任何引用C ++和通过ctypes调用的C ++代码抛出异常。看起来ctypes仅用于调用C函数,不处理C ++异常。


I'm playing a little bit with ctypes and C/C++ DLLs I have a quite simple "math" dll

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

    return a / b;
}

It works so far the only problem, i get a WindowsError Exception in Python and I cannot retrieve the text b cannot be zero Is there some special exception type I must throw? Or must the Python code be altered? python code:

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"

解决方案

First of all you should not use exception specifications in C++. This is a horrible feature of C++ and it has been deprecated in the latest standard. Also, the syntax throw(...) is not valid C++ at all, this line does not compile with a standard conforming compiler like gcc:

double Divide(double a, double b) throw (...)

I think you are relying on a non-standard Visual C++ "extension", which is, as far as I know, useless anyway, cause Visual C++ ignores all exception specifications unless throw() has no arguments.

Going through the ctypes documentation for Python 2.7.3 I can't see any reference to C++ and throwing exceptions from C++ code called via ctypes. It seems ctypes was meant for calling C functions only and does not handle C++ exceptions.

这篇关于Ctypes捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆