Python to C/C++ const char question
Asked Answered
D

2

8

I am extending Python with some C++ code.

One of the functions I'm using has the following signature:

int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
                                char *format, char **kwlist, ...);

(link: http://docs.python.org/release/1.5.2p2/ext/parseTupleAndKeywords.html)

The parameter of interest is kwlist. In the link above, examples on how to use this function are given. In the examples, kwlist looks like:

  static char *kwlist[] = {"voltage", "state", "action", "type", NULL};

When I compile this using g++, I get the warning:

warning: deprecated conversion from string constant to ‘char*’

So, I can change the static char* to a static const char*. Unfortunately, I can't change the Python code. So with this change, I get a different compilation error (can't convert char** to const char**). Based on what I've read here, I can turn on compiler flags to ignore the warning or I can cast each of the constant strings in the definition of kwlist to char *. Currently, I'm doing the latter. What are other solutions?

Sorry if this question has been asked before. I'm new.

Dyche answered 8/4, 2010 at 15:32 Comment(0)
T
4

Does PyArg_ParseTupleAndKeywords() expect to modify the data you are passing in? Normally, in idiomatic C++, a const <something> * points to an object that the callee will only read from, whereas <something> * points to an object that the callee can write to.

If PyArg_ParseTupleAndKeywords() expects to be able to write to the char * you are passing in, you've got an entirely different problem over and above what you mention in your question.

Assuming that PyArg_ParseTupleAndKeywords does not want to modify its parameters, the idiomatically correct way of dealing with this problem would be to declare kwlist as const char *kwlist[] and use const_cast to remove its const-ness when calling PyArg_ParseTupleAndKeywords() which would make it look like this:

PyArg_ParseTupleAndKeywords(..., ..., ..., const_cast<char **>(kwlist), ...);
Tramline answered 8/4, 2010 at 15:50 Comment(1)
I'm pretty sure PyArg_ParseTupleAndKeywords() does not expect to modify kwlist. Your suggestion is helpful. Thanks.Dyche
M
0

There is an accepted answer from seven years ago, but I'd like to add an alternative solution, since this topic seems to be still relevant.


If you don't like the const_cast solution, you can also create a write-able version of the string array.

char s_voltage[] = "voltage";
char s_state[] = "state";
char s_action[] = "action";
char s_type[] = "type";
char *kwlist[] = {s_voltage, s_state, s_action, s_type, NULL};

The char name[] = ".." copies the your string to a writable location.

Meneau answered 29/11, 2017 at 13:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.