【发布时间】:2017-11-13 07:41:50
【问题描述】:
我是 python 新手,最近使用 python 编程 CCD 相机拍照。我想使用 ctypes 调用 .so 文件中的函数。 函数原型为:
INT is_ImageFile (HIDS hCam, UINT nCommand, void* pParam, UINT cbSizeOfParam)
HIDS 是 uint 类型。官方给出的 c 代码示例是:
is_ImageFile(m_hCam, IS_IMAGE_FILE_CMD_SAVE, (void*)&ImageFileParams,
sizeof(ImageFileParams));
其中 ImageFileParams 是一个结构类型:
typedef struct{
wchar_t* pwchFileName;
UINT nFileType;
UINT nQuality;
char** ppcImageMem;
UINT* pnImageID;
BYTE reserved[32];}IMAGE_FILE_PARAMS;
在我的 .py 文件中,我尝试以这种方式定义结构:
class IMAGE_FILE_PARAMS(Structure):
_fields_=[("pwchFileNmae",c_wchar_p),("nFileType",c_uint),("nQuality",c_uint),("ppcImageMem",POINTER(c_char_p)),("pnImageID",POINTER(c_char_p)),("reserved",c_byte*32)]
并以这种方式定义一些成员:
ImageFileParams.pwchFileName = c_wchar_p("/home/user/aa.jpg")
ImageFileParams.nQuality=c_uint(80)
ImageFileParams.nFileType=c_uint(1)
然后调用函数:
is_ImageFile(hCam, IS_IMAGE_FILE_CMD_SAVE, cast(pointer(ImageFileParams),c_void_p),c_uint(sizeof(ImageFileParams)))
但我总是收到一个错误,表明参数无效。有什么问题?
【问题讨论】:
-
显示重现错误的最小完整示例,并给出完整的回溯。
-
请看SO: Python & Ctypes: Passing a struct to a function as a pointer to get back data。我相信,你必须用
CDLL()调用C 函数。恕我直言,Python ctypes API 无法检查您的 Python 绑定是否与 C 函数签名匹配。 (如果不是,您只是有未定义的行为,即包含所有内容:无法识别 -> 错误结果 -> 崩溃。)如果 Python 报告类型错误,这仅与“Python 端”有关。
标签: python c pointers ctypes .so