Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting PyCFunctionWithKeywords in PyMethodDef

Tags:

c++

python

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)

like image 257
Shep Avatar asked May 24 '26 16:05

Shep


2 Answers

Main Python implementation is written in C, not C++.

Thus, libpython code that evaluates keywdarg_methods[] is written in C and calls keywdarg_parrot via C calling conventions.

If you want C++ style integration with Python, find a way to use boost.python instead. Or perhaps cython.

like image 75
Dima Tisnek Avatar answered May 26 '26 04:05

Dima Tisnek


PyMethodDef is part of the Python C API so I would just use a C cast. It works and it's what all Python extenaions are using. Stay consistent.

Use C++ casts when working with objects that aren't part of the Python API.

like image 22
yak Avatar answered May 26 '26 06:05

yak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!