通过SWIG传递函数指针数组

Pass array of function pointers via SWIG

本文关键字:数组 指针 传递函数 SWIG 通过      更新时间:2023-10-16

在https://stackoverflow.com/a/22965961/353337的帮助下,我能够创建一个简单的示例,说明如何通过Python将一个函数指针传递给函数。具体地说,与

double f(double x) {
  return x*x;
}
double myfun(double (*f)(double x)) {
  fprintf(stdout, "%gn", f(2.0));
  return -1.0;
}
%module test
%{
#include "test.hpp"
%}
%pythoncallback;
double f(double);
%nopythoncallback;
%ignore f;
%include "test.hpp"

我可以调用

import test
test.f(13)
test.myfun(test.f)

并得到预期的结果。

现在,我想改变myfun的签名,以允许数组函数指针(都具有相同的签名),例如,

double myfun(std::vector<double (*)(double)>)

我如何适应.i文件?

理想情况下,Python调用将通过列表
test.myfun([test.f, test.g])

我制作了下面的测试用例来说明您要做的事情。它有一个真正的myfun(const std::vector<double(*)(double)>&)实现,使生活更有趣:

#include <vector>
double g(double x) {
  return -x;
}
double f(double x) {
  return x*x;
}
typedef double(*pfn_t)(double);
std::vector<double> myfun(const std::vector<pfn_t>& funs, const double d) {
  std::vector<double> ret;
  ret.reserve(funs.size());
  for(auto && fn : funs)
    ret.emplace_back(fn(d));
  return ret;
}

我原以为我们所需要做的就是使用:

%include <std_vector.i>
%template(FunVec) std::vector<double(*)(double)>;
%template(DoubleVec) std::vector<double>;
%include "test.h"

但是SWIG 3.0(来自Debian稳定版)不能正确处理这个FunVec,并且产生的模块无法编译。所以我添加了一个typemap作为解决方案:

%module test
%{
#include "test.h"
%}
%pythoncallback;
double f(double);
double g(double);
%nopythoncallback;
%ignore f;
%ignore g;
%typemap(in) const std::vector<pfn_t>& (std::vector<pfn_t> tmp) {
    // Adapted from: https://docs.python.org/2/c-api/iter.html
    PyObject *iterator = PyObject_GetIter($input);
    PyObject *item;
    if (iterator == NULL) {
      assert(iterator);
      SWIG_fail; // Do this properly
    }
    while ((item = PyIter_Next(iterator))) {
        pfn_t f;
        const int res = SWIG_ConvertFunctionPtr(item, (void**)(&f), $descriptor(double(*)(double)));
        if (!SWIG_IsOK(res)) {
          assert(false);
          SWIG_exception_fail(SWIG_ArgError(res), "in method '" "foobar" "', argument " "1"" of type '" "pfn_t""'");
        }
        Py_DECREF(item);
        tmp.push_back(f);
    }
    Py_DECREF(iterator);
    $1 = &tmp;
}
%include <std_vector.i>
// Doesn't work:
//%template(FunVec) std::vector<double(*)(double)>;
%template(DoubleVec) std::vector<double>;
%include "test.h"

基本上,所有这些都是为函数指针类型的向量添加一个'in'类型映射。该typemap只是对Python给出的输入进行迭代,并从Python可迭代对象构建一个临时的std::vector

这足以使以下Python按预期工作:

import test
print test.g
print test.f
print test.g(666)
print test.f(666)
print test.myfun([test.g,test.f],123)