I'm writing a python wrapper for a C++ DLL using ctypes. I've "flattened" the C++ Class to handle based C functions, and most of them are working well. There are a few weird functions in the class library that I'm unsure how to deal with though.
Here is the C++ version of the code I am trying to wrap:
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;
Now, I've "flattened" the classes methods to C functions like so:
typedef CVitCamDLL *CameraHandle;
#define EXPORTCALL __declspec(dllexport) __stdcall
CAM_HW EXPORTCALL GetCamParms(CameraHandle handle)
{
return *handle->GetCamParms();
}
I haven't sold myself on that method of wrapping it, but the compiler didn't complain so I took that as a good sign. My ability to debug C++ and C to an extent is based solely on what the compiler is yelling at me about, so this could be wrong?
Anyway, here is the Python code that I have since done to wrap it:
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))
Ok, so I was able to fix the memory access violation and I can read the data and everything which is fantastic. However, from the C++ use example, they use the GetCamParms function to also set the data, does anyone know if the ctypes return refers to the same block of memory and setting it works the same? (I'll test this to find out)
精彩评论