Ctypes catching exception

后端 未结 2 580
执笔经年
执笔经年 2020-12-21 01:51

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)
    {
       thro         


        
相关标签:
2条回答
  • 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.

    0 讨论(0)
  • 2020-12-21 02:40

    Try this:

    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"
    
    0 讨论(0)
提交回复
热议问题