pseudo
pseudo

Reputation: 385

Create an instance of Python New Style class to embed in C++

I am working with PyObject to embed part of the python code inside C++. I found the solution that works well with python 2.7 using PyInstance_New to create python instance. But it doesn't work with new style python classes which look like this.

    class B(object): 
      def __init__(self, name): 
        self.name = name

      def print_name(lastName): 
        print self.name + " " + lastName

In my older code(python 2.7), class definition doesn't inherit from object class and I create my instance to call print_name method like this. P.S. file name is A.py.

    PyObject *import, *attr, *instance, *methodcall, *arg, *tuple;
    arg = PyString_FromString("hello"); 
    tuple = PyTuple_Pack(1, arg);  

    import = PyImport_ImportModule("A"); 
    attr = PyObject_GetAttrString(import, "B");
    instance = PyInstance_New(attr, arg, NULL); 

    methodcall = PyObject_CallMethod(instance, (char *) "print_name", (char *) "(s)", (char *) "Bill"); 

But the code above doesn't work anymore because, in the new python 3.x, type(class) returns object, instead of instance. Now, I am getting this error.

bad argument to internal function.

Any help is appreciated. Thank you.

Upvotes: 2

Views: 2454

Answers (1)

Barpaum
Barpaum

Reputation: 111

I'm not sure whether this works for you. But I suggest you try it. Just use "PyObject_CallObject" to initialize an instance, then use "PyObject_CallMethod" to call a method of the instance.

Upvotes: 1

Related Questions