2013-01-31 36 views
2

我正在写一个嵌入Python代码的小程序(下图)。在C++中嵌入python:分配C++和python变量

#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'的值。 有没有办法做到这一点?

在此先感谢。

+2

看看:http://docs.python.org/2/extending/embedding.html 你也可以看看的boost ::这使得它非常容易... ... http://www.boost.org/doc/libs/1_52_0/libs/python/doc/tutorial/doc/html/index.html –

回答

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); 
+0

太棒了!那工作..非常感谢:) – Vigo