1

I am using a C++ program and I need to call Python objects from the C++ program (to perform optimization and mathematical operations). I am having trouble to pass arguments to Python object via C++ Here is a simple code

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

and the python class

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

Unfortunately, the argument x does not go through the python method add (when i call PyObject_CallMethod(pInstance, "add","i",x)) Calling the print method via python gives me "the sum via the Python class is 0". What is the best way to provide a number to a python method ?

Thanks a lot for your help

Vincent

PS : I defined a double add function in python as

def add2(self,x,y):
    print "double adding via python"
    self.sum += x*y

Calling the following in C++

PyObject_CallMethod(pInstance, "add2","(ii)",x,2);

is working... It seems that I have a problem with the format (i).

ifconfig
  • 6,242
  • 7
  • 41
  • 65
Vincent
  • 1,616
  • 2
  • 16
  • 18

2 Answers2

1

According to the docs of PyObject_CallMethod, the format string should produce a tuple. Also, don't ignore the return value. Try

PyObject *pValue;
pValue = PyObject_CallMethod(pInstance, "add","(i)",x);
if (pValue)
    Py_DECREF(pValue);
else
    PyErr_Print();
Janne Karila
  • 24,266
  • 6
  • 53
  • 94
  • The OP should *never* ignore the return value. This could cause a lot of bugs to happen due to not proper exception handling. – Bakuriu May 16 '13 at 10:26
  • thanks for your answers ! About the return value, should I just add a reference PyObject *pValue and call the method add as follows : pValue = PyObject_CallMethod(pInstance, "add","i",x); ? Unfortunately I tried inputing the format as a integer tuplet (i) but it does not work – Vincent May 16 '13 at 10:29
0

What worked for me was something like this python init and method:

class SwiftApi:
    def __init__(self, user, key):
        self.user = user
        self.key = key

the python method

def get_object(self, container, obj, resp_chunk_size=None,
               query_string=None):
    return 'some returned object here'

I was able to call the function from c++ code with this hack

#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- %s\n", md_module);
}
else{ printf ("NO md_module ");}

if (!(attr = PyObject_GetAttrString(md_module, "ObjectStorageMiddleware")))
    error_abort();

if (attr != 0) {
printf ("got the class- %s\n", attr);
}
if (!(instance = PyObject_CallObject(attr, args )))
    error_abort();
if (instance != 0) {
printf ("###############got it ObjStrgRes instance -  class- %d\n", (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);
Ohad the Lad
  • 1,889
  • 1
  • 15
  • 24