Passing python objects as arguments to C/C++ function using ctypes

筅森魡賤 提交于 2019-11-28 11:38:05

问题


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.


回答1:


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 )


来源:https://stackoverflow.com/questions/11213072/passing-python-objects-as-arguments-to-c-c-function-using-ctypes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!