2011-08-09 15 views
1

我有幾個數據類型,我都包裹着Python和ctypes的C庫 - 工作得非常好!在C我有以下(示意圖)代碼:調用從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類型包裹類Type1和Type2使用from_param()方法:

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()'方法接受None作爲arg2參數,但是ctypes嘗試調用None對象的from_param()方法 - 顯然會失敗。

所以 - 我想我的問題是:是否有可能得到ctypes的函數調用的代碼只是傳遞NULL時,它得到一個無輸入參數?

喬金 -

回答

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 

與同爲類型2。

+0

OK;這很有趣。我有大約15個from_param()作爲實例方法的情況,並且這對我很好(除非這個實例是None問題)。我按照你的建議做了,而且效果很好。謝謝! – user422005

+0

我認爲它可以在大多數情況下工作:當'obj'是'Type'的一個實例時'Type.method(obj)'和'obj.method()'是可以互換的,但ctypes也可以調用'Type.method obj)'當obj是一個不同的類型時,比如'None',這就是你所遇到的。 – Duncan

+0

@eryksun謝謝:更正。這就是爲什麼當我無法測試代碼示例時,我總是寫'未經測試'。 – Duncan

0

也許你可以無轉換爲類型2呼叫前:

cfunc_some_function(self , Type2(arg2)) 

和Type2.from_param()返回cfunc_some_function合適的對象()。

相關問題