bbd*_*e95 11 c++ python python-module
我正在尝试使用此函数在我的一个c ++程序中从python加载一个函数
char * pyFunction(void)
{
char *my_result = 0;
PyObject *module = 0;
PyObject *result = 0;
PyObject *module_dict = 0;
PyObject *func = 0;
PyObject *pArgs = 0;
module = PyImport_ImportModule("testPython");
if (module == 0)
{
PyErr_Print();
printf("Couldn't find python module");
}
module_dict = PyModule_GetDict(module);
func = PyDict_GetItemString(module_dict, "helloWorld");
result = PyEval_CallObject(func, NULL);
//my_result = PyString_AsString(result);
my_result = strdup(my_result);
return my_result;
}
Run Code Online (Sandbox Code Playgroud)
我应该使用什么而不是PyString_AsString?
use*_*450 16
根据您的helloWorld()函数返回的类型,它可能会有所不同,所以最好检查它.
要处理返回的str(Python 2 unicode),您需要对其进行编码.编码将取决于您的用例,但我将使用UTF-8:
if (PyUnicode_Check(result)) {
PyObject * temp_bytes = PyUnicode_AsEncodedString(result, "UTF-8", "strict"); // Owned reference
if (temp_bytes != NULL) {
my_result = PyBytes_AS_STRING(temp_bytes); // Borrowed pointer
my_result = strdup(my_result);
Py_DECREF(temp_bytes);
} else {
// TODO: Handle encoding error.
}
}
Run Code Online (Sandbox Code Playgroud)
要处理返回的bytes(Python 2 str),您可以直接获取字符串:
if (PyBytes_Check(result)) {
my_result = PyBytes_AS_STRING(result); // Borrowed pointer
my_result = strdup(my_result);
}
Run Code Online (Sandbox Code Playgroud)
此外,如果您收到非字符串对象,则可以使用PyObject_Repr(),PyObject_ASCII(),PyObject_Str()或PyObject_Bytes()进行转换.
所以最后你可能想要这样的东西:
if (PyUnicode_Check(result)) {
// Convert string to bytes.
// strdup() bytes into my_result.
} else if (PyBytes_Check(result)) {
// strdup() bytes into my_result.
} else {
// Convert into your favorite string representation.
// Convert string to bytes if it is not already.
// strdup() bytes into my_result.
}
Run Code Online (Sandbox Code Playgroud)