gpt4 book ai didi

python - 如何通过 C++ 在 Python 函数中传递字符串参数

转载 作者:行者123 更新时间:2023-11-30 04:42:30 24 4
gpt4 key购买 nike

Image shows the output. I am expecting "Hai" to be printed. But its printing some number如何通过 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");

根据 the Py_BuildValue documentation "(i)" 格式适用于整数元组,而不是字符串。

您需要使用 "s" 作为空终止 C 字符串的格式。

关于python - 如何通过 C++ 在 Python 函数中传递字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58708093/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com