5

我正在使用 python ctypes 和 libc 与供应商提供的 DLL 文件进行交互。DLL 文件的目的是从相机获取图像。

图像采集似乎运行没有错误;我遇到的问题是访问数据。

图像采集函数将 ctypes.c_void_p 作为图像数据的参数。

简化如下:

"""
typedef struct AvailableData
{
    void* initial_readout;
    int64 readout_count;
} imageData;
"""

class AvailableData(ctypes.Structure):
    _fields_ = [("initial_readout", ctypes.c_void_p), 
                ("readout_count", ctypes.c_longlong)]

"""
Prototype
Acquire(
CamHandle                 camera,
int64                       readout_count,
int                       readout_time_out,
AvailableData*         available,
AcquisitionErrorsMask* errors );
"""

>>> imageData = AvailableData()
>>> Acquire.argtypes = CamHandle, ctypes.c_longlong, ctypes.c_int, 
         ctypes.POINTER(AvailableData), ctypes.POINTER(AcquisitionErrorsMask)
>>> Acquire.restype = ctypes.c_void_p

>>> status = Acquire(camera, readout_count, readout_time_out, imageData, errors)

我不完全理解该函数在做什么,因为在我运行该函数之后,它imageData.initial_readout似乎是一个类型“long”(甚至不是 ctypes.c_long:只是“long”)。但是,它也有一个与之相关的值。我假设这是存储数据的起始地址。

>>> type(imageData.initial_readout)
<type 'long'>
>>> imageData.initial_readout
81002560L

我目前访问数据的方法是使用 libc.fopen、libc.fwrite、libc.fclose,如下所示:

>>> libc = ctypes.cdll.msvcrt

>>> fopen = libc.fopen
>>> fwrite = libc.fwrite
>>> fclose = libc.fclose
>>> fopen.argtypes = ctypes.c_char_p, ctypes.c_char_p
>>> fopen.restype = ctypes.c_void_p

>>> fopen.restype = ctypes.c_void_p
>>> fwrite.argtypes = ctypes.c_void_p, ctypes.c_size_t, ctypes.c_size_t, ctypes.c_void_p
>>> fwrite.restype = ctypes.c_size_t

>>> fclose = libc.fclose
>>> fclose.argtypes = ctypes.c_void_p,
>>> fclose.restype = ctypes.c_int

>>> fp = fopen('output3.raw', 'wb')
>>> print 'fwrite returns: ',fwrite(ctypes.c_void_p(imageData.initial_readout), readoutstride.value, 1, fp)
fwrite returns:  0
>>> fclose(fp)

其中readoutstride = 2097152对应于 16 位像素的 1024x1024 阵列。

文件“output3.raw”显示在 Windows 资源管理器中,但是,它有 0 kbytes,当我尝试使用(例如使用 imag 查看器)打开它时,它说文件是空的。

我看到fwrite返回值 0(但应该返回值 1)

如果您对我在这里做错了什么有任何想法,我将不胜感激。先感谢您。

4

1 回答 1

6

Specify argtypes, restype of the functions.

import ctypes

libc = ctypes.windll.msvcrt

fopen = libc.fopen
fopen.argtypes = ctypes.c_char_p, ctypes.c_char_p,
fopen.restype = ctypes.c_void_p

fwrite = libc.fwrite
fwrite.argtypes = ctypes.c_void_p, ctypes.c_size_t, ctypes.c_size_t, ctypes.c_void_p
fwrite.restype = ctypes.c_size_t

fclose = libc.fclose
fclose.argtypes = ctypes.c_void_p,
fclose.restype = ctypes.c_int

fp = fopen('output3.raw', 'wb')
fwrite('Hello', 5, 1, fp)
fclose(fp)
于 2013-06-23T05:15:27.930 回答