0

I have a dll with a function that takes PyObject as argument something like

void MyFunction(PyObject* obj)
{
    PyObject *func, *res, *test;

    //function getAddress of python object
    func = PyObject_GetAttrString(obj, "getAddress");

    res = PyObject_CallFunction(func, NULL);
    cout << "Address: " << PyString_AsString( PyObject_Str(res) ) << endl;
}

and I want to call this function in the dll from python using ctypes

My python code looks like

import ctypes as c

path = "h:\libTest"
libTest = c.cdll.LoadLibrary( path )

class MyClass:
    @classmethod
    def getAddress(cls):
        return "Some Address"

prototype = c.CFUNCTYPE(    
    c.c_char_p,                
    c.py_object
)

func = prototype(('MyFunction', libTest))

pyobj = c.py_object(MyClass)
func( c.byref(pyobj) )

there is some problem in my Python code when I run this code I got message like

WindowsError: exception: access violation reading 0x00000020

Any suggestion to improve python code would be appriciated.

Maverick
  • 366
  • 1
  • 5
  • 11
  • I suppose `PyObject_GetAttrString(Class, "getAddress")` is really `PyObject_GetAttrString(obj, "getAddress")`? I also suppose that you check every function result, and none of them is a null up until `cout <<`? – 9000 Jun 26 '12 at 20:01
  • Yes Its a typo. Thanks. I'll fix it. Apart from that the C code is fine. I am having trouble with the python part. Passing pointer to the python objects from Python to that c function. How ? – Maverick Jun 26 '12 at 20:29
  • Hmm, I don't know for real, but I _think_ `byref` is not needed here. I suppose that just `func(pyobj)` should work. With `byref` the C code gets a pointer to a pointer. – 9000 Jun 26 '12 at 20:42

1 Answers1

4

I made the following changes to your code and it worked for me, but I'm not sure it is 100% correct way to do it:

  1. Use PYFUNCTYPE.
  2. Just pass the python class object.

For example:

prototype = c.PYFUNCTYPE(    
    c.c_char_p,                
    c.py_object
)

func = prototype(('MyFunction', libTest))

func( MyClass )
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • Yes It worked for me too, Thanks. But could you please explain whats the difference between c.PYFUNCTYPE and c.CFUNCTYPE. How would I know which one to choose ? – Maverick Jun 27 '12 at 13:22
  • I couldn't find much in the documentation, other than it doesn't release the GIL (global interpreter lock). Since your DLL was using the Python API and passing python objects, it seemed a good choice. – Mark Tolonen Jun 27 '12 at 13:34