【问题标题】:Embedding python in C++: Assigning C++ and python variables在 C++ 中嵌入 python:分配 C++ 和 python 变量
【发布时间】:2013-01-31 16:53:38
【问题描述】:

我正在编写一个将 python 嵌入到 C++ 代码中的小程序(如下所示)。

#include <Python.h>

int main()     
{

    int x;
    Py_Initialize();

    const char* pythonScript = "print 'Start'"
    PyRun_SimpleString(pythonScript);

    /*
    assign a python variable 'n' to 'x' i.e n=x
    */

    Py_Finalize();
    return 0; 

}

我在这里的要求是我将 python 变量“n”分配给 C++ 变量“x”的值。 有没有办法做到这一点?

提前致谢。

【问题讨论】:

标签: python embedding


【解决方案1】:

以下片段应该可以工作(未经测试):

PyObject *main = PyImport_AddModule("__main__"); // borrowed
if (main == NULL)
    error();
PyObject *globals = PyModule_GetDict(main); // borrowed
PyObject *value = PyInt_FromLong(x);
if (value == NULL)
   error();
if (PyDict_SetItemString(globals, "n", value) < 0)
   error();
Py_DECREF(value);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-11
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多