Я не хотел бы продолжать преобразовывать каждый строковый объект Python из PyObject*
в std::string
или char*
с PyUnicode_DecodeUTF8 и PyUnicode_AsUTF8 , поскольку это дорогостоящая операция.
На мой последний вопрос Как расширить / повторно использовать реализацию Python C Extensions / API? , мне удалось использовать функцию Python open
, чтобы напрямую дать мне строку PyObject*
.Сделав это, очень просто отправить строку обратно в программу Python, потому что я могу просто передать ее указатель PyObject*
, вместо того, чтобы делать полную закадровую копию, как PyUnicode_DecodeUTF8
или PyUnicode_AsUTF8
.
В реализации regex
API CPython я могу найти функцию , подобную этой :
static void* getstring(PyObject* string, Py_ssize_t* p_length,
int* p_isbytes, int* p_charsize,
Py_buffer *view)
{
/* given a python object, return a data pointer, a length (in
characters), and a character size. return NULL if the object
is not a string (or not compatible) */
/* Unicode objects do not support the buffer API. So, get the data directly. */
if (PyUnicode_Check(string)) {
if (PyUnicode_READY(string) == -1)
return NULL;
*p_length = PyUnicode_GET_LENGTH(string);
*p_charsize = PyUnicode_KIND(string);
*p_isbytes = 0;
return PyUnicode_DATA(string);
}
/* get pointer to byte string buffer */
if (PyObject_GetBuffer(string, view, PyBUF_SIMPLE) != 0) {
PyErr_SetString(PyExc_TypeError, "expected string or bytes-like object");
return NULL;
}
*p_length = view->len;
*p_charsize = 1;
*p_isbytes = 1;
if (view->buf == NULL) {
PyErr_SetString(PyExc_ValueError, "Buffer is NULL");
PyBuffer_Release(view);
view->buf = NULL;
return NULL;
}
return view->buf;
}
Кажется, она не использует PyUnicode_DecodeUTF8
илиPyUnicode_AsUTF8
для работы с PyObject*
от Python Interpreter.
Как я могу использовать базовые строковые операции со строками PyObject*
без преобразования, а затем std::string
или char*
?
Я бы назвал базовые операции в следующих примерах: (просто для примера, я использую Py_BuildValue для построения строки PyObject*
из строки как char*
или std::string
)
static PyObject* PyFastFile_do_concatenation(PyFastFile* self)
{
PyObject* hello = Py_BuildValue( "s", "Hello" );
PyObject* word = Py_BuildValue( "s", "word" );
// I am just guessing the `->value` property
PyObject* hello_world = hello->value + word->value;
hello_world; // return the `PyObject*` string `Hello word`
}
static PyObject* PyFastFile_do_substring(PyFastFile* self)
{
PyObject* hello = Py_BuildValue( "s", "Hello word" );
PyObject* hello_world = hello->value[5:];
hello_world; // return the `PyObject*` string `word`
}
static PyObject* PyFastFile_do_contains(PyFastFile* self)
{
PyObject* hello = Py_BuildValue( "s", "Hello word" );
if( "word" in hello->value ) {
Py_BuildValue( "p", true ); // return the `PyObject*` boolean `true`
}
Py_BuildValue( "p", false ); // return the `PyObject*` boolean `false`
}