Pass array of function pointers through SWIG

With the help of https://stackoverflow.com/a/166269/2128/, I was able to create a simple example of how to pass a single pointer to a function through Python. In particular, with

double f(double x) {
  return x*x;
}

double myfun(double (*f)(double x)) {
  fprintf(stdout, "%g\n", f(2.0));
  return -1.0;
}
%module test

%{
#include "test.hpp"
%}

%pythoncallback;
double f(double);
%nopythoncallback;

%ignore f;
%include "test.hpp"

I can call

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

and get the expected results.

Now I would like to change the signature myfunto allow an array of function pointers (all with the same signature), e.g.

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

How do I set up a file .i?

Ideally, the Python call will be through a list

test.myfun([test.f, test.g])
+4
source share
1 answer

, , . 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 , . - :

%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"

"" typemap . , Python, std::vector Python.

, 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)
+1

Source: https://habr.com/ru/post/1651837/


All Articles