I am trying to expose a c++ function to python using cython as follows:
from libcpp.vector cimport vector
cdef extern from "auction.h":
cpdef double util(
int q,
int sq,
double alpha,
double beta,
double kappa,
int s,
int ss,
int m,
const vector[double]& p,
double a0);
I am getting the following (not very descriptive) error:
src\\RFQLib.pyx:4:21: Cannot convert 'double (int, int, double, double, double, int, int, int, const vector[double] &, double)' to Python object
What's the problem here?
Thanks in advance for all your help.
You have to first tell Cython about the function (through the cdef exetern from
mechanism) and then create a Cython function that calls it, and it's this you can use from Python:
from libcpp.vector cimport vector
cdef extern from "auction.h":
double util(
int q,
int sq,
double alpha,
double beta,
double kappa,
int s,
int ss,
int m,
const vector[double]& p,
double a0);
def py_util(int q,
int sq,
double alpha,
double beta,
double kappa,
int s,
int ss,
int m,
p,
double a0):
cdef vector[double] p_vec = p
return util(q,sq,alpha,beta,kappa,s,ss,m,p_vec,a0)
The slight complication is the conversion to a C++ vector<double>
. Cython can automatically convert lists/tuples containing appropriate types to vectors. The flipside is that this is done every time you call py_util
and so probably a bit slow. It's also a problem if util
stores the reference for use later (probably unlikely, but always possible!) since p_vec
will have ceased to exist by then.
Two other options are to create a Cython class that wraps vector[double]
. This is clearly a bit more work for you, but avoids a type conversion on every call of py_util
. Alternatively you might be able to modify util
so it uses a double*
, and use numpy arrays or python arrays on the Python side.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.