Search code examples
pythoncctypesword-wrap

how to properly wrap C API in python using ctypes?


I have wrapped two API's from a C library in Python using ctypes. One works and the other doesn't. My question is: how do I properly wrap API from from a C library in Python using ctypes?

some background info:

import ctypes 
from ctypes import *

MF = (b'path_to_file') 
beginTime = (-Value)
endTime = (Value)
PN = (b'path_to_String')
DT_RETURNGMT = 0x0100
DT_FLOAT = 0x0001
convert = DT_RETURNGMT|DT_FLOAT

This one works:

#read functions
dll.openFile.argtypes = c_char_p,
dll.openFile.restype = POINTER(File)

dll.freeFile.argtypes = POINTER(File),
dll.freeFile.restype = None
f = dll.openFile(MF)
print(f[0].fileInfo[0].items)

This one does not:

#retrieve data
dll.readSP.argtypes = POINTER(File), c_char_p(PN), 
c_double(beginTime), c_double(endTime),
0, 0, 
c_ushort(convert),
dll.readSP.restype = POINTER(SP)
#pointer to the SP file structure 
g = dll.readSP(f, MF)
print(g)
print(g[0].points)
pint(g[0].tStamp[0].data[0].TTag)

I think the pointer is correct because when I tell the code to print(g) it returns the location of my SP object like this:

<__main__.LP_SP object at 0x000001D1EAB862C8>

but it cant return the location of anything else in the SP file structure. Which leads me to believe it is how I wrapped the API that is the problem. But i'm not sure where I went wrong with it.

I think that I must not have wrapped the API correctly but i'm not sure where I went wrong. double *refTIME, and struct TimeTage *refGMT are NULL in the C code so I have them as 0 in my script.


Solution

  • You've defined instances instead of types in the non-working code. Instead of:

    dll.readSP.argtypes = POINTER(File), c_char_p(PN), c_double(beginTime), c_double(endTime), 0, 0, c_ushort(convert),
    

    You need:

    dll.readSP.argtypes = POINTER(File), c_char_p, c_double, c_double, c_double, POINTER(TTag), c_ushort