3

I've seen here that you can do

from libcpp.string cimport string
from libcpp.vector cimport vector

to refer to parameters of type std::string and std::vector. I need to pass functions to a c++ method expecting std::function<>. I tried doing

from libcpp.function cimport function

but that didn't work:

from libcpp.function cimport function
^
------------------------------------------------------------

cython_topics.pyx:3:0: 'libcpp/function/function.pxd' not found
Traceback (most recent call last):
  File "setup.py", line 18, in <module>
    language="c++",                   # generate and compile C++ code
  File "/usr/lib64/python2.7/site-packages/Cython/Build/Dependencies.py", line 934, in cythonize
    cythonize_one(*args)
  File "/usr/lib64/python2.7/site-packages/Cython/Build/Dependencies.py", line 1056, in cythonize_one
    raise CompileError(None, pyx_file)
Cython.Compiler.Errors.CompileError: cython_topics.pyx

What's the right way to call a c++ function expecting std::function<>?

Stephen
  • 2,613
  • 1
  • 24
  • 42
  • Must you use cython? You can handle that easily in C++ code, have a look at [PyObject_Call](https://docs.python.org/3/c-api/object.html#c.PyObject_Call). – YiFei Feb 27 '17 at 01:20
  • @YiFei I have a boost-python wrapper for a fairly large c++ library. I'm experimenting with Cython to see if it it is an acceptable option for an updated wrapping platform for an updated version of the library. So, no. I don't have to use Cython, but the question is aimed to determine if Cython is capable of wrapping C++ methods which expect std::function as parameter types. – Stephen Feb 27 '17 at 01:48
  • You want to call python function in C++ as std::function? Then I suppose that's not quite possible. (I'm not sure though) Considering that python dynamically defined functions are not even compiled, thus there's virtually no way to be run in C++ directly. Yet boost.python has boost::python::call as a wrapper. – YiFei Feb 27 '17 at 02:07
  • @YiFei yup, I've been calling python functions just fine from C++ with boost::python::call. Sounds like you think that this cannot be done with Cython? – Stephen Feb 27 '17 at 02:12
  • Pretty much, the error traceback you posted seems like it's not supported yet in Cython (I know little about Cython). But I think you can have a specialized invoke function on Python function and wait for Cython to support them:) – YiFei Feb 27 '17 at 02:23
  • There isn't really a simple solution. You can do it if you're prepared to write a small wrapper yourself, or if you keep the boost dependency for this bit (and you can quite happily mix boost and Cython in this way) – DavidW Feb 27 '17 at 08:44
  • Thanks @DavidW your answer looks like exactly what I'm looking for. – Stephen Feb 27 '17 at 15:53

0 Answers0