开发者

Python to C/C++ const char question

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 wha开发者_如何学编程t 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.


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), ...);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜