简体   繁体   中英

How to insert a python code in C++?

i am trying to embed a code python in c++. I have this python code :

#include <Python.h>

int main(int arg)
{
    Py_SetProgramName(argv[0]);
    Py_Initialize();
    PyRun_SimpleString("from time import time,ctime\n"
                       "print 'Today is',ctime(time())\0");
    Py_Finalize();
    return 0;
}

but what i want is something like that :

include

int main(int arg)
{
    Py_SetProgramName(argv[0]);
    int a = 5;
    Py_Initialize();
    PyRun_SimpleString("a = " + a);
    Py_Finalize();
    return 0;
}

but it does not work. I mean i want with python to display the value of the variable a. Thank you :)

您可以使用std :: to_stringint转换为字符串,然后使用std :: string :: c_str在函数调用期间将临时const char*转换为内部数据:

PyRun_SimpleString(("a = " + std::to_string(a)).c_str());

You have to use correct C syntax in the C code; in C, "a = "+a does not concatenate strings (as you might assume), but calculate a useless pointer that points a bytes behind the start of the constant string "a = " . With a being 5 , there is nothing useful at that place.

Concatenating strings is not that straightforward in C; you need to handle preparing memory for the target, etc.; same for converting a number to a string. For example:
char buffer[30];
sprintf(buffer,"a = %d\\n",a);

and then
PyRun_SimpleString(buffer);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM