Passing a restricted method in Cython as an argument

I am trying to port some C ++ code to Cython, and I came up with some problems trying to pass a method from a class as an argument to a function.

I don’t know if this makes it more understandable, but class A is a statistical model (therefore myAMethod uses not only the arguments passed, but also many instance variables), and B has various methods to minimize the function passed.

In C ++, I have something like this style: class A { public: double myAMethod(double*) }; class B { public: double myBMethod(A&, double (A::*f) (double*) }

So, I'm trying to use instances of A and B in Cython code. I didn’t have to transfer classes, but when I try to use myBMethod I don’t know how to pass the view pointerA::*myAMethod

: myBMethod(ptrToAObj[0], &ptrToAObj.myAMethod) Cython [...] &ptrToAObj->myAMethod [...], , g++:

"ISO ++ - -."

myBMethod(ptrToAObj[0], A.myAMethod), Cython ,

myAMethod A.

, . ++ , A B Python ( Cython), . , , / - SO, Cython Smith Cython, . !

+4
1

( ) . , , .

cpp_bit.hpp:

class A { 
  public:
    double myAMethod(double*) { return 0.0; }
}; 

typedef double (A::*A_f_ptr)(double *);

class B {
 public:
   double myBMethod(A& a, A_f_ptr f) { 
     double x = 0.1;
     return (a.*f)(&x);
   }
};

A_f_ptr getAMethod() {
  return &A::myAMethod;
}

, . , myAMethod. , .

py_bit.pyx

# distutils: language = c++

from cython.operator import dereference

cdef extern from "cpp_bit.hpp":
  cdef cppclass A:
    double myAMethod(double*)

  cdef cppclass A_f_ptr:
    pass

  cdef cppclass B:
    double myBMethod(A&, A_f_ptr)

  cdef A_f_ptr getAMethod()

cdef class PyA:
  cdef A* thisptr
  def __cinit__(self):
    self.thisptr = new A()
  def __dealloc__(self):
    del self.thisptr
  cpdef myAMethod(self,double[:] o):
    return self.thisptr.myAMethod(&o[0])

cdef class PyB:
  cdef B* thisptr
  def __cinit__(self):
    self.thisptr = new B()
  def __dealloc__(self):
    del self.thisptr
  cpdef myBMethod(self,PyA a):
    return self.thisptr.myBMethod(dereference(a.thisptr),getAMethod())

, typedef - Cython, cppclass . , cython , cpp_bit.hpp( ), .

, , - - ++ ( getAMethod, ). , ++ -, . , , .

, : (Edit: , ! !)

++, myBMethod

double myBMethod(std::function<double (double*)>)

( A, ). - ++ (11!), A

b.myBMethod([&](double* d){ return a.myAMethod(d) };

Cython, , double (double*) ++, .

, , , .

+1

All Articles