简体   繁体   English

在 Python3 中将 C++ 中的 std::string 转换为 PyObject

[英]Convert std::string to PyObject in C++ in Python3

I am trying to convert std::string to PyObject .我正在尝试将std::string to PyObject转换std::string to PyObject

std::string st = jsp.updateRoot(people, people);
PyObject* pValue = PyBytes_AsString(st);

It is not working using the above method.使用上述方法不起作用。

How can I convert?我该如何转换?

From doc.:来自文档:

char* PyBytes_AsString(PyObject *o) char* PyBytes_AsString(PyObject *o)

Return a pointer to the contents of o.返回指向 o 内容的指针。 The pointer refers to the internal buffer of o, which consists of len(o) + 1 bytes.指针指向o的内部缓冲区,由len(o)+1个字节组成。 The last byte in the buffer is always null, regardless of whether there are any other null bytes.缓冲区中的最后一个字节始终为空,无论是否有任何其他空字节。 The data must not be modified in any way, unless the object was just created using PyBytes_FromStringAndSize(NULL, size).不得以任何方式修改数据,除非该对象刚刚使用 PyBytes_FromStringAndSize(NULL, size) 创建。 It must not be deallocated.它不能被解除分配。 If o is not a bytes object at all, PyBytes_AsString() returns NULL and raises TypeError.如果 o 根本不是字节对象,则 PyBytes_AsString() 返回 NULL 并引发 TypeError。

This is the wrong direction in OP's case.在 OP 的情况下,这是错误的方向。

The function for the opposite conversion is相反转换的函数是

PyObject* PyBytes_FromString(const char *v) PyObject* PyBytes_FromString(const char *v)

Return value: New reference.返回值:新引用。

Return a new bytes object with a copy of the string v as value on success, and NULL on failure.返回一个新的字节对象,其中包含字符串 v 的副本作为成功时的值,失败时返回 NULL。 The parameter v must not be NULL;参数 v 不能为 NULL; it will not be checked.它不会被检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM