2016-04-26 65 views
1

我目前正試圖使用​​ctypes來連接以下庫(http://sol.gfxile.net/escapi/),但我不確定如果我做錯了什麼或者庫沒有像我期望的那樣工作(樣本C應用程序似乎工作)ctypes返回空值int指針的指針

還有就是你是爲了傳遞給initCapture,看起來像這樣

struct SimpleCapParams 
{ 
    /* Target buffer. 
    * Must be at least mWidth * mHeight * sizeof(int) of size! 
    */ 
    int * mTargetBuf; 
    /* Buffer width */ 
    int mWidth; 
    /* Buffer height */ 
    int mHeight; 
}; 

這是我目前的代碼結構:

from ctypes import cdll, Structure, c_int, POINTER, cast, c_long, pointer 

class SimpleCapParams(Structure): 
    _fields_ = [ 
     ("mTargetBuf", POINTER(c_int)), 
     ("mWidth", c_int), 
     ("mHeight", c_int) 
    ] 

width, height = 512, 512 
array = (width * height * c_int)() 
options = SimpleCapParams() 
options.mWidth = width 
options.height = height 
options.mTargetBuf = array 

lib = cdll.LoadLibrary('escapi.dll') 
lib.initCOM() 
lib.initCapture(0, options) 
lib.doCapture(0) 
while lib.isCaptureDone(0) == 0: 
    pass 

print options.mTargetBuf 

lib.deinitCapture(0) 

但是,mTargetBuf中的所有值都是0.我是否稱這個錯誤或其他事情發生了?

這是什麼,我需要做的(不ASCII)一個C++例子:https://github.com/jarikomppa/escapi/blob/master/simplest/main.cpp

+1

的例子傳遞'&capture'因爲原型是'INT initCapture(無符號整數deviceno,結構SimpleCapParams * aParams)'。因此'選項'必須通過引用傳遞,而不是按值傳遞。 'lib.initCapture(0,ctypes.byref(options))'。 – eryksun

+0

謝謝,但仍然似乎返回0.做options.mTargetBuf.contents返回'c_long(0)' –

+0

您需要檢查'initCapture'是否失敗,即它是否返回0.此外,您可以使用'array'而不是'options.mTargetBuf',這是更安全的,因爲數組大小。使用'options.mTargetBuf [i]'可以讀取數組以外的內容和潛在的段錯誤。 – eryksun

回答

2

所以看來我應該檢查我的代碼:)

options.height = heightoptions.mHeight = height按我的結構。

byref也有幫助。

工作代碼:

from ctypes import * 

width, height = 512, 512 

class SimpleCapParms(Structure): 
    _fields_ = [ 
     ("mTargetBuf", POINTER(c_int)), 
     ("mWidth", c_int), 
     ("mHeight", c_int), 
    ] 

array_type = (width * height * c_int) 
array = array_type() 
options = SimpleCapParms() 
options.mWidth = width 
options.mHeight = height 
options.mTargetBuf = array 

lib = cdll.LoadLibrary('escapi.dll') 
lib.initCapture.argtypes = [c_int, POINTER(SimpleCapParms)] 
lib.initCapture.restype = c_int 
lib.initCOM() 

lib.initCapture(0, byref(options)) 
lib.doCapture(0) 

while lib.isCaptureDone(0) == 0: 
    pass 

print(array[100]) 

lib.deinitCapture(0)