Pass std::string into PyObject_CallFunction
Pass std::string into PyObject_CallFunction
当我运行pResult = PyObject_CallFunction(pFunc, "s", &"String")
时,python脚本返回正确的字符串。但是,如果我试着运行这个:
std::string passedString = "String";
pResult = PyObject_CallFunction(pFunc, "s", &passedString)
然后将结果转换为std::string
,当我打印它时,我得到<NULL>
。以下是返回<NULL>
的一些(可能)完整代码:
#include <Python.h>
#include <string>
#include <iostream>
int main()
{
PyObject *pName, *pModule, *pDict, *pFunc;
// Set PYTHONPATH TO working directory
setenv("PYTHONPATH",".",1); //This doesn't help
setenv("PYTHONDONTWRITEBYTECODE", " ", 1);
// Initialize the Python Interpreter
Py_Initialize();
// Build the name object
pName = PyUnicode_FromString((char*)"string");
// Load the module object
pModule = PyImport_Import(pName);
// pDict is a borrowed reference
pDict = PyModule_GetDict(pModule);
// pFunc is also a borrowed reference
pFunc = PyDict_GetItemString(pDict, (char*)"getString");
if (pFunc != NULL)
{
if (PyCallable_Check(pFunc))
{
PyObject *pResult;
std::string passedString = "String";
pResult = PyObject_CallFunction(pFunc, "s", &passedString);
PyObject* pResultStr = PyObject_Repr(pResult);
std::string returnedString = PyUnicode_AsUTF8(pResultStr);
std::cout << returnedString << std::endl;
Py_DECREF(pResult);
Py_DECREF(pResultStr);
}
else {PyErr_Print();}
}
else {std::cout << "pFunc is NULL!" << std::endl;}
// Clean up
Py_DECREF(pFunc);
Py_DECREF(pDict);
Py_DECREF(pModule);
Py_DECREF(pName);
// Finish the Python Interpreter
Py_Finalize();
}
Python脚本(string.py):
def getString(returnString):
return returnString
我在Ubuntu (linux)上使用Python 3.4
您应该将c风格的字符串传递给PyObject_CallFunction
以使您的代码工作。为了从std::string
中获得c-string,请使用c_str()
方法。所以下面这行:
pResult = PyObject_CallFunction(pFunc, "s", &passedString);
应该像这样:
pResult = PyObject_CallFunction(pFunc, "s", passedString.c_str());
相关文章:
- 相当于 pybind11 中的 boost::p ython py::scope().attr()
- 如何构建一个 setup.py 来编译C++使用 Python、pybind11 和 Mingw-w64 的扩展?
- 如何应用 printers.py 修改?(Linux操作系统)
- 通过 sh 导入模块错误运行.py脚本
- 链接 library.lib 使用 setup.py.
- pybind 如何对 py::list 对象进行操作
- 返回多个 py::数组而不在 pybind11 中复制
- 如何在 module.reload() 之后保持 py::objects 存活
- pybind11:属性错误:尝试从 py 文件运行函数时,模块'XXX'没有属性'YYY'
- 通往GCC_ARM之路 (mbed_settings.py)
- 如何从 python (py) 文件调用 C++ 函数
- 使用参数调用C 的gdal_merge.py
- 如何在python文件中访问c ++头文件(.py)
- 当我使用py 生成时,然后在macOS上boost.python包装器时,我会发现有关std :: string的错
- 在同一目录中使用conanfile.txt和conanfile.py
- 从C 运行.py脚本
- 扩展安装工具扩展以在 setup.py 中使用 CMake
- 提升 Python 如何在导入的 Python 文件中导入 py
- cocos2dx重置或更改setup.py中Android的环境变量
- SublimeLinter(ST3/ST2) for C++ (cppcheck/cppint.py)