具有不同结构点的函数的Swig包装器

2024-04-24 04:56:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想包装下面的C函数。注意,从Foo\u t*到Bar\u t*的类型转换:

void function(Foo_t * f) {
      Bar_t * b = (Bar_t *) f;  // casting is done in C original code
      //do sth with b
}

Swig生成一个遵循以下模式的包装器:

void wrap_function( Foo_t *foo ) {
     function(foo);
}

但在python中,我想使用Bar\t实例调用我的包装器函数:

b = Bar_t()
function(b) 

所以,我开始了以下类型映射:

%typemap(in) Foo * {
  Bar_t *temp;
  int res0 = 0;
  Foo_t *arg = 0;

  res0 = SWIG_ConvertPtr($input, (void **) &temp, $descriptor(Bar_t *), 0|0);
    if (!SWIG_IsOK(res0)) {
        SWIG_exception_fail(SWIG_ArgError(res0), "in method '" "function" "', argument " "1"" of type '" "Bar_t *""'"); 
    } 
     $1 = (Foo_t *) temp;
     function(arg);
}

但是抛出了异常!你知道吗

我怎样才能从酒吧到餐厅?你知道吗


Tags: 函数infooisargbarfunctiontemp
1条回答
网友
1楼 · 发布于 2024-04-24 04:56:20

如果让typemap期望一个Python条形图包装Foo*输入,那么就不能将Foo*传递给Foo*输入。相反,请导出强制转换辅助对象。注意%inline表示法实现并导出内容的包装器。你知道吗

测试.h

#ifdef _WIN32
#   ifdef EXPORT
#       define API __declspec(dllexport)
#   else
#       define API __declspec(dllimport)
#   endif
#else
#   define API
#endif

typedef struct Foo {
    int a;
} Foo_t;

typedef struct Bar {
    int b;
} Bar_t;

API void function(Foo_t * f);

测试.c

#define EXPORT
#include <stdio.h>
#include "test.h"

API void function(Foo_t * f) {
      Bar_t * b = (Bar_t *) f;  // casting is done in C original code
      // do something with b
}

测试.i

%module test

%{
#include "test.h"
%}

%inline %{
Foo_t* Foo_cast(Bar_t* bar) {
    return (Foo_t*)bar;
}
%}

%include "test.h"

测试:

>>> import test
>>> bar = test.Bar_t()
>>> test.function(test.Foo_cast(bar))
>>> foo = test.Foo_t()
>>> test.function(foo)
>>>

相关问题 更多 >