2

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.

pseudo
  • 385
  • 2
  • 19
  • 1
    Possible duplicate of [Create an object using Python's C API](http://stackoverflow.com/questions/4163018/create-an-object-using-pythons-c-api) – Uyghur Lives Matter Nov 17 '16 at 14:41
  • 1
    As the linked question and [Barpaum](http://stackoverflow.com/a/40655558/369450) suggest, you should do: `instance = PyObject_CallObject(attr /*the class*/, tuple /*args in tuple*/);` – Uyghur Lives Matter Nov 17 '16 at 14:47

1 Answers1

1

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.

Barpaum
  • 111
  • 7