【问题标题】:SWIG Python - wrapping a function that expects a double pointer to a structSWIG Python - 包装一个需要指向结构的双指针的函数
【发布时间】:2012-11-14 14:42:09
【问题描述】:

我正在包装一个包含结构的 C 库:

struct SCIP
{
//...
}

以及创建这样一个结构的函数:

void SCIPcreate(SCIP** s)

SWIG 从中生成一个 python 类 SCIP 和一个函数 SCIPcreate(*args)

当我现在尝试在 python 中调用SCIPcreate() 时,它显然需要SCIP** 类型的参数,我应该如何创建这样的东西?

或者我应该尝试使用自动调用SCIPcreate() 的构造函数扩展SCIP 类吗?如果是这样,我会怎么做?

【问题讨论】:

    标签: python pointers swig


    【解决方案1】:

    给定头文件:

    struct SCIP {};
    
    void SCIPcreate(struct SCIP **s) {
      *s = malloc(sizeof **s);
    }
    

    我们可以使用以下方法包装这个函数:

    %module test
    %{
    #include "test.h"
    %}
    
    %typemap(in,numinputs=0) struct SCIP **s (struct SCIP *temp) {
      $1 = &temp;
    }
    
    %typemap(argout) struct SCIP **s {
      %set_output(SWIG_NewPointerObj(SWIG_as_voidptr(*$1), $*1_descriptor, SWIG_POINTER_OWN));
    }
    
    %include "test.h"
    

    这是两个类型映射,一个用于创建一个本地临时指针,用作函数的输入,另一个用于将调用后指针的值复制到返回中。

    作为替代方案,您还可以使用%inline 设置重载:

    %newobject SCIPcreate;
    %inline %{
      struct SCIP *SCIPcreate() {
        struct SICP *temp;
        SCIPcreate(&temp);
        return temp;
      }
    %}
    

    【讨论】:

      猜你喜欢
      • 2019-01-18
      • 2016-01-26
      • 2019-07-01
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 2011-11-30
      • 1970-01-01
      相关资源
      最近更新 更多