I made the following test case to illustrate what you're trying to do. It has a real implementation of myfun(const std::vector<double(*)(double)>&)
to make life a little more interesting:
#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;
}
I expected that all we'd need to do to make this work is use:
%include <std_vector.i>
%template(FunVec) std::vector<double(*)(double)>;
%template(DoubleVec) std::vector<double>;
%include "test.h"
However SWIG 3.0 (from Debian stable) doesn't handle this FunVec
correctly and the resulting module doesn't compile. So I added a typemap as a workaround:
%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"
Basically all this does is add one 'in' typemap for the vector of function pointer types. That typemap just iterates over the input given from Python and builds a temporary std::vector
from a Python iterable.
This is sufficient that the following Python works as expected:
import test
print test.g
print test.f
print test.g(666)
print test.f(666)
print test.myfun([test.g,test.f],123)