我正在使用 C++ 程序,我需要从 C++ 程序调用 Python 对象(以执行优化和数学运算)。我无法通过 C++ 将参数传递给 Python 对象 这是一个简单的代码
#include <Python.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
int main()
{
PyObject *pName, *pModule, *pDict, *pClass, *pInstance;
// Initialize the Python interpreter
Py_Initialize();
// Build the name object
pName = PyString_FromString("Adder");
// 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);
}
else
{
std::cout << "Cannot instantiate the Python class" << std::endl;
}
int sum = 0;
int x;
for (size_t i = 0 ; i < 5 ; i++)
{
x = rand() % 100;
sum += x;
PyObject_CallMethod(pInstance, "add","(i)",x);
}
PyObject_CallMethod(pInstance, "printSum", NULL);
std::cout << "the sum via C++ is " << sum << std::endl;
std::getchar();
Py_Finalize();
}
和Python类
class Adder:
# Constructor
def __init__(self):
self.sum = 0
# Add an element to the Adder
def add(self,x):
print "adding via python ", x
self.sum += x
# Print the total sum
def printSum(self):
print "the sum via the Python class is ",self.sum
不幸的是,参数 x 没有通过 python 方法 add (当我调用 PyObject_CallMethod(pInstance, "add","i",x) 时)通过 python 调用 print 方法给了我“通过 Python 类求和”是 0”。向 python 方法提供数字的最佳方式是什么?
非常感谢您的帮助
文森特
PS:我在Python中定义了一个双加函数为
def add2(self,x,y):
print "double adding via python"
self.sum += x*y
在 C++ 中调用以下内容
PyObject_CallMethod(pInstance, "add2","(ii)",x,2);
正在工作...我的格式 (i) 似乎有问题。
请您参考如下方法:
根据the docs of PyObject_CallMethod ,格式字符串应该生成一个元组。另外,不要忽略返回值。尝试一下
PyObject *pValue;
pValue = PyObject_CallMethod(pInstance, "add","(i)",x);
if (pValue)
Py_DECREF(pValue);
else
PyErr_Print();






