Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass string arguments in Python function via C++

Tags:

c++

python

Image shows the output. I am expecting "Hai" to be printed. But its printing some numberHow to pass string argument to python function via c++

I tried below code. It can pass double, float, int , bool values. But when it pass string value its printed as numbers which seems to be a memory location Python.py is my script file name

class Adder:
    # Constructor
    def __init__(self):
        self.sum = 0

    def disp(self, param1):
        print("Parameter is: ", param1)
void ExecutePyMethodeWitStringArg()
{
    PyObject *pName, *pModule, *pDict, *pClass, *pInstance;

    // Initialize the Python interpreter
    Py_Initialize();

    // Build the name object
    pName = PyUnicode_FromString("Python");
    // Load the module object
    pModule = PyImport_Import(pName);
    // pDict is a borrowed reference
    pDict = PyModule_GetDict(pModule);
    // Build the name of a callable class
    pClass = PyDict_GetItemString(pDict, "Adder");


    // Create an instance of the class
    if (PyCallable_Check(pClass))
    {
        pInstance = PyObject_CallObject(pClass, NULL);

        PyObject_CallMethod(pInstance, "disp", "(i)", "Hai");


    }
    else
    {
        std::cout << "Cannot instantiate the Python class" << std::endl;
    }
    std::getchar();
    Py_Finalize();
}
like image 214
Hari Sankar v m Avatar asked Aug 06 '26 11:08

Hari Sankar v m


1 Answers

The problem is a mismatching format specifier and argument type:

    PyObject_CallMethod(pInstance, "disp", "(i)", "Hai");

According to the Py_BuildValue documentation the format "(i)" would be for a tuple of integers, not a string.

You need to use "s" for the format for a null-terminated C string.

like image 131
Some programmer dude Avatar answered Aug 08 '26 00:08

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!