%和类型映射异常%错误codeS从SWIG,Python的C函数 [英] %typemap and %exception for error codes from C functions for SWIG, Python

查看:154
本文介绍了%和类型映射异常%错误codeS从SWIG,Python的C函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些C code,我要公开到Python。它有一个调用约定是这样的:

I've got some C code that I want to expose to Python. It has a calling convention like this:

int add(int a, int b, int *err)

在这里的返回值是(A + B)或什么,但如果出事了,那么我会得到* ERR错误code。我想,这样它的行为像这样,从Python的角度来包装这个功能:

where the return value would be (a+b) or whatever, but if something went wrong, then I would get an error code in *err. I want to wrap this function so that it behaves like this, from the Python perspective:

def add(a,b):
    if something_bad:
        raise RuntimeError("something bad")
    return a+b

这应该很容易,对不对?但我没有找到它如此。

This should be easy, right? But I'm not finding it so.

下面的东西,我有工作,但看的出来的 myerr3 杂牌组装电脑:

Here is something that I have that works, but look out for the myerr3 kludge:

%module myswig
%feature("autodoc","1");

%{
int add(int a, int b, int *err){
    if(a < 0)*err = 1;
    if(b < 0)*err = 2;
    return a+b;
}

char *err_string(int err){
    switch(err){
    case 1:return "first argument was less than 0";
    case 2:return "second argument was less than 0";
    default:return "unknown error";
    }
}
%}

%typemap(in,numinputs=0) int *err (int myerr = 0){
    $1 = &myerr;
};

%exception{
    $action
    if(myerr3 != 0){
        PyErr_SetString(PyExc_RuntimeError,err_string(myerr3));
        return NULL;
    }
};

int add(int a, int b, int *err);

此行​​为,因为它应该,例如,使用

This behaves as it should, eg with

import myswig
print "add(1,1) = "
print myswig.add(1,1)
# prints '2'

print "add(1,-1) = "
print myswig.add(1,-1)
# raises an exception

# we never get here...
print "here we are"

但我真的不能使用此解决方案,因为如果我有像

but I can't really use this solution, because if I have another function like

int add(int a, int b, int c, int *err)

然后我的 myerr3 杂牌将打破。

什么是解决这个问题的更好的方法,在不改变C code的调用约定?

What's the better way to solve this problem, without changing the calling convention of the C code?

推荐答案

卡尔Wette,通过痛饮用户邮件列表:

From Karl Wette, via the swig-user mailing list:

您可以通过移动的声明修改,在类型映射
  myerr类型映射里面:

You could modify your "in" typemap by moving the declaration of "myerr" inside the typemap:

%typemap(in,numinputs=0, noblock=1) int *err {
   int myerr = 0;
   $1 = &myerr;
};


  
  

只要有只有一个诠释* ERR在每个函数参数,这
  应该罚款。然后,您可以使用myerr没有直接的说法
  号。

So long as there's only one "int *err" argument in each function, this should be fine. You can then use "myerr" directly without the argument number.

这似乎是完全正确的解决方案,无需组装机。感谢卡尔!

This seems to be exactly the right solution, no kludges required. Thanks Karl!

这篇关于%和类型映射异常%错误codeS从SWIG,Python的C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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