我有一个 C 程序,它从我的相机获取图像并将二进制数据写入文件。
我(迄今为止没有成功)试图编写一个python脚本来模仿C代码。
Python ctypes 示例似乎执行没有错误,直到我尝试将其写入文件。换句话说,在 Python 中,fwrite
在这种情况下无法将数据写入文件。 fwrite
返回 的值0
,指示0
文件已写入。
所以,我要问以下问题: 由于我有一个外部 c 函数正在读取二进制数据,大概是内存中的某个缓冲区,Python ctypes 的实例是否可能根本没有对该内存位置的读取访问权限?如果是这种情况,python ctypes 是否有可能获得访问内存中适当区域所需的权限?
作为参考,我包含了一个(按预期工作)简化的 C 示例,后面是下面的 Python ctypes 示例,它打开并创建了适当的文件,但不写入它。
//Data Saving Sample
//The sample will open the first camera attached
//and acquire 3 frames. The 3 frames will be saved
//in a raw format and can be opened with applications
//such as image-j
#define NUM_FRAMES 3
#define NO_TIMEOUT -1
#include "stdio.h"
#include "picam.h"
#include <iostream>
using namespace std;
int main()
{
// The following structure contains the image data
AvailableData data;
int readoutstride = 2097152;
FILE *pFile;
Acquire( NUM_FRAMES, NO_TIMEOUT, &data, &errors );
pFile = fopen( "sampleX3.raw", "wb" );
if( pFile )
{
fwrite( data.initial_readout, 1, (NUM_FRAMES*readoutstride), pFile );
fclose( pFile );
}
}
这是我的 Python 版本:
""" Load the picam.dll """
picamDll = 'DLLs/Picam.dll'
picam = ctypes.cdll.LoadLibrary(picamDll)
libc = ctypes.cdll.msvcrt
fopen = libc.fopen
data = AvailableData()
readoutstride = ctypes.c_int(2097152)
"""
This is the C-structure form from the provided header file, followed by the Python syntax for creating the same structure type
typedef struct AvailableData
{
void* initial_readout;
int64 readout_count;
} AvailableData;
class AvailableData(ctypes.Structure):
_fields_ = [("initial_readout", ctypes.c_void_p), ("readout_count",ctypes.c_int64)]
"""
"""
Simplified C-Prototype for Acquire
Acquire(
int64 readout_count,
int readout_time_out,
AvailableData* available);
"""
picam.Acquire.argtypes = int64, int, ctypes.POINTER(AvailableData)
picam.Acquire.restype = int
print picam.Acquire( 3, -1, ctypes.byref(data), ctypes.byref(errors))
""" Write contents of Data to binary file """
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_int
fclose = libc.fclose
fclose.argtypes = ctypes.c_void_p,
fclose.restype = ctypes.c_int
fp = fopen('PythonBinOutput.raw', 'wb')
print 'fwrite returns: ',fwrite(data.initial_readout, 3*readoutstride.value, 1, fp)
fclose(fp)