简体   繁体   English

如何将SwigPyObject强制转换为ctypes void *

[英]How to cast a SwigPyObject to ctypes void*

I have a python, ctypes wrapped function to a C API taking a void* parameter for a class X, eg C: 我有一个python,将ctypes包装的函数包装到C API中,该类采用类X的void *参数,例如C:

myFunc(void* aXHandle); //where X is a class, of class X.

For the class X, I have access to a swigged API and can get the myX.this, which is of type SwigPyObject. 对于类X,我可以访问Swigged API,并可以获取myX.this,其类型为SwigPyObject。

How do I cast this so I can call my C-API function using ctypes and using a ctypes c_void_p as an argument? 如何进行转换,以便可以使用ctypes并将ctypes c_void_p用作参数来调用C-API函数? In Python, I thought something like: aXObjectThis = myX.this 在Python中,我想到的是:aXObjectThis = myX.this

myHandle = cast(aXObjectThis, c_void_p)

but that does not work; 但这不起作用; getting "wrong type in argument 1" 收到“参数1输入错误的类型”

The __int__ method of SwigPyObject is handled by SwigPyObject_long , defined in pyrun.swg . __int__的方法SwigPyObject由处理SwigPyObject_long ,在定义pyrun.swg It returns PyLong_FromVoidPtr(v->ptr) , so you should be able to use the following: 它返回PyLong_FromVoidPtr(v->ptr) ,因此您应该可以使用以下代码:

myHandle = c_void_p(int(myX.this))

More conveniently ctypes looks for an _as_parameter_ attribute. ctypes更方便地寻找_as_parameter_属性。 You could set this on the instance or as a property: 您可以在实例上设置它或将其设置为属性:

type(myX)._as_parameter_ = property(
    lambda self: c_void_p(int(self.this)))

The simply call myFunc(myX) . 只需调用myFunc(myX)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM