python - 具有不同结构指针的函数的 Swig 包装器

标签 python c swig

我想包装以下 C 函数。注意,从 Foo_t * 到 Bar_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);
}

但是抛出了异常!

如何从 Bar_t * 转换为 Foo_t * ?

最佳答案

如果您制作类型映射以期望 Foo* 输入的 Python Bar_t 包装器,您将无法将 Foo* 传递给 Foo* 输入。相反,导出一个 cast 助手。请注意 %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)
>>>

关于python - 具有不同结构指针的函数的 Swig 包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54574792/

相关文章:

c - 我如何在递归中找到索引

python - 训练集和测试集中不同数量的特征 - 随机森林 sklearn Python

返回意外结果的 Python 3 正则表达式

c - 在没有文件的情况下链接 gcc 中的共享库?

c++ - 通过 GLSL 将 YV12 转换为 RGB 的问题

c++ - cmake + 痛饮 + 依赖项

python - SWIG 3 使用模板化构造函数包装未模板化的类

java - SWIG 类型映射 uint8_t* 从 C/C++ 到 java.nio.ByteBuffer

python - 如何在 60 分钟的时间间隔内随机分配 100 个 API 调用?

Python tkinter 错误消息