从ctypes调用C函数:类实例可以是None

时间:2011-08-09 07:40:43

标签: python c ctypes

我有一个包含几种数据类型的C库,我用Python和ctypes包装 - 效果非常好!在C中,我有以下(示意图)代码:

typedef struct type1_struct type1_t;
typedef struct type2_struct type2_t;  

void some_function( type1_t *t1 , type2_t *t2) {  
  if (t2 == NULL) {  
     // Do whatever  
  } else {  
     // 
  }
}  

此代码的要点是some_function()可以将NULL作为t2参数的值。在Python中,type1_t和type2_t类型使用from_param()方法包装类Type1和Type2:

Class Type1:
   def from_param(self):
       return self.c_ptr


   def call_some_func(self , arg2 = None):
       # This fails when the python/ctypes tries to
       # lookup the from_param() method and arg2 is None. 
       cfunc_some_function( self , arg2 )     


lib_handle = ctypes.CDLL( lib )
cfunc_some_function = getattr( lib_handle , "some_function")
cfunc_some_function.argtypes = [Type1 , Type2]

因此初始化cfunc_some_function函数以将Type1和Type2实例作为参数,然后ctypes层将调用两个输入参数的from_param()方法;但是我希望Type1类的'call_some_func()'方法接受arg2参数的None,但是ctypes尝试调用None对象的from_param()方法 - 这显然是失败的。

所以 - 我想我的问题是:是否有可能让ctypes函数调用代码在获得None输入参数时只传递NULL?

Joakim

2 个答案:

答案 0 :(得分:3)

from_param()方法需要是类方法,但您已将其定义为实例方法。将其更改为classmethod并检查参数是否为无。

像(未经测试)的东西:

class Type1:
   @classmethod
   def from_param(cls, obj):
       if obj is None:
           return c_void_p()
       else:
           return obj.c_ptr

和Type2相同。

答案 1 :(得分:0)

也许你可以在调用之前将None转换为Type2:

cfunc_some_function( self , Type2(arg2) )  

和Type2.from_param()返回cfunc_some_function()的正确对象。