Search code examples
c++python-c-api

How do I pass a variable through Python using C++ in Python.h


I wanted to try out embedding Python into C++. I was able to get that to work but I wanted to start writing prints with variables which are in declared in c++. For example:

(C++)

int num = 43;
PyRun_SimpleString("print("+num+")");
char g;
std::cin>>g;
PyRun_SimpleString("print("+g+")");

I tried to figure out how to use other related functions, but I don't seen to find enough information.


Solution

  • To pass char,

    Python script:

    def test(person):
        return "Hello " + person;
    

    C++:

    PyObject *pName, *pModule, *pFunc, *pArgs, *pValue;
    pName = PyUnicode_FromString((char*)"script");
    pModule = PyImport_Import(pName);
    pFunc = PyObject_GetAttrString(pModule, (char*)"test");
    pArgs = PyTuple_Pack(1, PyUnicode_FromString((char*)"User"));
    pValue = PyObject_CallObject(pFunc, pArgs);
    auto result = _PyUnicode_AsString(pValue);
    std::cout << result << std::endl;
    

    Output:

    Hello User
    

    To pass integer it's the same like above. Here you are passing over double 2.0.

    pArgs = PyTuple_Pack(1,PyFloat_FromDouble(2.0));
    pValue = PyObject_CallObject(pFunc, pArgs);
    

    You can refer to all the apis here >> https://docs.python.org/3/c-api/