通过c++在Python函数中传递参数
Passing arguments in Python function via C++
我正在使用一个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中定义了一个double add函数def add2(self,x,y):
print "double adding via python"
self.sum += x*y
在c++中调用以下代码
PyObject_CallMethod(pInstance, "add2","(ii)",x,2);
工作……似乎我对格式(I)有问题。
根据PyObject_CallMethod
的文档,格式字符串应该产生一个元组。另外,不要忽略返回值。试着
PyObject *pValue;
pValue = PyObject_CallMethod(pInstance, "add","(i)",x);
if (pValue)
Py_DECREF(pValue);
else
PyErr_Print();
为我工作的是像这样的python init和方法:
class SwiftApi:
def __init__(self, user, key):
self.user = user
self.key = key
python方法
def get_object(self, container, obj, resp_chunk_size=None,
query_string=None):
return 'some returned object here'
我可以用这个hack从c++代码中调用这个函数
#include <python2.7/Python.h>
void error_abort(void)
{
PyErr_Print();
exit(EXIT_FAILURE);
}
int main (int argc, char *argv[])
{
PyObject *user, *key, *args, *md_module, *attr, *instance, *get_obj_tuple, *container, *obj,*methodcall,
Py_Initialize();
if (!(user = PyString_FromString("test:tester")))
error_abort();
if (!(key = PyString_FromString("testing")))
error_abort();
if (!(args = PyTuple_Pack(5,type, user, key, secret_key, authurl)))
error_abort();
PySys_SetPath("the path where the py file lives");
if (! (md_module = PyImport_ImportModule("SwiftApi")))
error_abort();
if (md_module != 0) {
printf ("got it middleware_module- %sn", md_module);
}
else{ printf ("NO md_module ");}
if (!(attr = PyObject_GetAttrString(md_module, "ObjectStorageMiddleware")))
error_abort();
if (attr != 0) {
printf ("got the class- %sn", attr);
}
if (!(instance = PyObject_CallObject(attr, args )))
error_abort();
if (instance != 0) {
printf ("###############got it ObjStrgRes instance - class- %dn", (long)instance);
}
if (!(container = PyString_FromString("my-con-55")))
error_abort();
if (!(obj = PyString_FromString("ohad2.jpg")))
error_abort();
get_container_tuple = PyTuple_Pack(1, container);
get_obj_tuple = PyTuple_Pack(1, obj);
if (!(methodname = PyString_FromString("get_object")))
error_abort();
methodcall = PyObject_CallMethodObjArgs(instance, methodname, get_container_tuple, get_obj_tuple, NULL);
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类