3

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(); } 
2

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.