Recently I’ve been wrapping a lot of C++ code in python, and I find this block (taken directly from the python documentation) a bit troubling:
static PyMethodDef keywdarg_methods[] = {
/* The cast of the function is necessary since PyCFunction values
* only take two PyObject* parameters, and keywdarg_parrot() takes
* three.
*/
{"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
"Print a lovely skit to standard output."},
{NULL, NULL, 0, NULL} /* sentinel */
};
The issue is the line which casts kwarg_parrot, of type PyCFunctionWithKeywords to a PyCFunction.
Coming from a C++ background (and given that I am wrapping C++ code), it seems wrong to use a C-style cast. I’ve tried static_cast, and dynamic_cast, both of which cause the compiler to complain (with good reason, this really is an unsafe cast in the general sense). The only viable C++ option seems to bereinterpret_cast, but so far as I can tell this is a more verbose version of a C-style cast.
Granted, the above is wrapped in an extern "C" block, so maybe the C way is the correct way. Does anyone have any better ideas? (What I’d really like to see would be a solution that could automatically generate the doc string based on the keywords.)
Unfortunately, solutions like Boost.Python and SWIG are off the table. (I’m working within an ugly framework)
Main Python implementation is written in C, not C++.
Thus, libpython code that evaluates
keywdarg_methods[]is written in C and callskeywdarg_parrotvia C calling conventions.If you want C++ style integration with Python, find a way to use boost.python instead. Or perhaps cython.