使用ctypes将python对象作为参数传递给C/C ++函数 [英] Passing python objects as arguments to C/C++ function using ctypes

查看:426
本文介绍了使用ctypes将python对象作为参数传递给C/C ++函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有以PyObject作为参数的函数的dll. 像

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;
}

我想使用ctypes在python的dll中调用此函数

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

我的python代码看起来像

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) )

我的Python代码有问题 当我运行此代码时,我收到类似

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

WindowsError:异常:读取读取0x00000020的访问冲突

WindowsError: exception: access violation reading 0x00000020

任何改进python代码的建议都会被采纳.

Any suggestion to improve python code would be appriciated.

推荐答案

我对您的代码进行了以下更改,并且对我有用,但是我不确定这是100%正确的方法:

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. 使用PYFUNCTYPE.
  2. 只需传递python类对象即可.

例如:

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

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

func( MyClass )

这篇关于使用ctypes将python对象作为参数传递给C/C ++函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆