gpt4 book ai didi

Python C/API 分配一个 C++ 变量

转载 作者:行者123 更新时间:2023-11-30 04:09:47 24 4
gpt4 key购买 nike

我正在使用 Python C/API 编写一个小程序,它基本上调用一个简单的 Python 脚本。这是代码:

#include <Python.h>

PyObject *pName, *pModule, *pDict, *pFunc;

int main() {

Py_Initialize();
pName = PyString_FromString("simplemodule");
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, "simplefunction");

if(PyCallable_Check(pFunc)) {

PyObject_CallObject(pFunc, NULL);


} else {

PyErr_Print();

}

Py_DECREF(pName);
Py_DECREF(pModule);

Py_Finalize();

return 0;
}

现在,这是 simplemodule.py 的代码:

def simplefunction():
m = 5*5
return m

我的问题是:如何将变量 m 分配给 C++ 变量,以便我可以在 C++ 中使用它?

最佳答案

使用PyInt_AsLong将返回值转换为 C long。

...
if (PyCallable_Check(pFunc)) {
PyObject *res = PyObject_CallObject(pFunc, NULL);
if (res != NULL) {
long n = PyInt_AsLong(res); // <---------
cout << n << endl;
} else {
PyErr_Print();
}
...

关于Python C/API 分配一个 C++ 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20948583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com