o.z
o.z

Reputation: 1156

boost::python passing argv to C++

I have a C++ project and I want to give a python-API to it - I provide a shared library which the user imports in his python project. The C++ code parses the CLI, so I need to pass the C++ side (from the python-API) argv as char**, and not as a list. Any suggestions?

Upvotes: 0

Views: 288

Answers (1)

user4815162342
user4815162342

Reputation: 155216

Here is a function written using the regular Python/C API (untested). Feel free to adapt to boost::python constructs as appropriate:

char **list_to_argv_array(PyObject *lst)
{
  assert (PyList_Check(lst));       // use better error handling here
  size_t cnt = PyList_GET_SIZE(lst);
  char **ret = new char*[cnt + 1];
  for (size_t i = 0; i < cnt; i++) {
    PyObject *s = PyList_GET_ITEM(lst, i);
    assert (PyString_Check(s));     // likewise
    size_t len = PyString_GET_SIZE(s);
    char *copy = new char[len + 1];
    memcpy(copy, PyString_AS_STRING(s), len + 1);
    ret[i] = copy;
  }
  ret[cnt] = NULL;
  return ret;
}

When the array is no longer needed, deallocate it by delete[]-ing all the individual members, as well as the array itself.

Upvotes: 3

Related Questions