ctypes返回空值int指针的指针
问题描述:
我目前正试图使用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
答
所以看来我应该检查我的代码:)
options.height = height
应options.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)
的例子传递'&capture'因为原型是'INT initCapture(无符号整数deviceno,结构SimpleCapParams * aParams)'。因此'选项'必须通过引用传递,而不是按值传递。 'lib.initCapture(0,ctypes.byref(options))'。 – eryksun
谢谢,但仍然似乎返回0.做options.mTargetBuf.contents返回'c_long(0)' –
您需要检查'initCapture'是否失败,即它是否返回0.此外,您可以使用'array'而不是'options.mTargetBuf',这是更安全的,因为数组大小。使用'options.mTargetBuf [i]'可以读取数组以外的内容和潜在的段错误。 – eryksun