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.

2
  • 1
    Possible duplicate of Create an object using Python's C API Commented Nov 17, 2016 at 14:41
  • 1
    As the linked question and Barpaum suggest, you should do: instance = PyObject_CallObject(attr /*the class*/, tuple /*args in tuple*/); Commented Nov 17, 2016 at 14:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.