该图显示了输出。我希望将印刷“海”字。但是它打印一些数字如何通过C ++将字符串参数传递给python函数
我尝试下面的代码。它可以传递double,float,int,bool值。但是当它传递字符串值时,它打印为数字,这似乎是一个内存位置Python.py是我的脚本文件名
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();
}
问题是格式说明符和参数类型不匹配:
PyObject_CallMethod(pInstance, "disp", "(i)", "Hai");
根据该Py_BuildValue
文件的格式"(i)"
将是整数的元组,而不是一个字符串。
您需要使用"s"
以null终止的C字符串的格式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句