【问题标题】:Python C/API assign a C++ variablePython C/API 分配一个 C++ 变量
【发布时间】:2014-01-06 11:00:59
【问题描述】:

我正在用 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++ 中使用它?

【问题讨论】:

    标签: python c++ python-c-api


    【解决方案1】:

    使用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();
        }
        ...
    

    【讨论】:

    • 谢谢!它完美地工作。如果模块函数返回一个字符串,我应该使用PyString_AsString之类的东西吗?
    • @jndok,是的,使用PyString_AsString。顺便说一句,它返回 char *,而不是 C++ string
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 2018-06-13
    • 1970-01-01
    • 2019-05-11
    相关资源
    最近更新 更多