我正在使用 ctypes 为 C++ DLL 编写一个 python 包装器。我已经“扁平化”了 C++ 类来处理基于 C 的函数,并且它们中的大多数都运行良好。类库中有一些奇怪的函数,但我不确定如何处理。
这是我要包装的代码的 C++ 版本:
typedef struct {
short Valid; // magic number
short SizeX,SizeY;
short Fps;
short Shutter1,Shutter2; //Preview 1 and 2 Shutter, in lines (=ShutterTime[sec]*Fps*SizeY)
short PreTrigPages;
short Options;
short BufStart;
short BufEnd;
short SeqLength;
short ShiftCount;
short DBS;
short FN;
short MAXBL;
} CAM_PARMS_V1;
union CAM_PARMS {
CAM_PARMS_V1 p;
BYTE bytes[128];
unsigned long quads[32];
};
//Function prototype
virtual CAM_PARMS *GetCamParms(void);
//Use of function
GetCamParms()->p.SizeX=640;
现在,我已经将类方法“扁平化”为 C 函数,如下所示:
typedef CVitCamDLL *CameraHandle;
#define EXPORTCALL __declspec(dllexport) __stdcall
CAM_HW EXPORTCALL GetCamParms(CameraHandle handle)
{
return *handle->GetCamParms();
}
我没有用那种包装它的方法推销自己,但编译器没有抱怨,所以我认为这是一个好兆头。我在一定程度上调试 C++ 和 C 的能力完全取决于编译器对我大喊大叫的内容,所以这可能是错误的吗?
无论如何,这是我用来包装它的 Python 代码:
import ctypes as ct
from ctypes.util import find_library
dll = find_library('VitCamC')
if dll == None:
raise Exception("VitCamC.dll not found")
cam = ct.WinDLL(dll)
class CAM_PARMS_V1(ct.Structure):
_fields_ = [("Valid", ct.c_short),
("SizeX", ct.c_short),
("SizeY", ct.c_short),
("Fps", ct.c_short),
("Shutter1", ct.c_short),
("Shutter2", ct.c_short),
("PreTrigPages", ct.c_short),
("Options", ct.c_short),
("BufStart", ct.c_short),
("BufEnd", ct.c_short),
("SeqLength", ct.c_short),
("ShiftCount", ct.c_short),
("DBS", ct.c_short),
("FN", ct.c_short),
("MAXBL", ct.c_short)]
class CAM_PARMS(ct.Union):
_fields_ = [("p", CAM_PARMS_V1),
("bytes", ct.c_ubyte * 128),
("quads", ct.c_ulong * 32)]
def get_cam_parms(handle, mode):
cam.GetCamParms.restype = CAM_PARMS #This fixes it!
return cam.GetCamHw(handle, ct.byref(mode))
好的,所以我能够修复内存访问冲突,我可以读取数据和所有很棒的东西。但是,从 C++ 使用示例中,他们使用 GetCamParms 函数来设置数据,有谁知道 ctypes 返回是否指的是同一块内存并且设置它的工作方式相同吗?(我将对此进行测试以找出答案)