python函数传入对象_使用ctypes将python对象作为参数传递给C / C ++函数

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.

解决方案

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:

Use PYFUNCTYPE.

Just pass the python class object.

For example:

prototype = c.PYFUNCTYPE(

c.c_char_p,

c.py_object

)

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

func( MyClass )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值