[ctypes-users] comments on this ctypes static variable idiom?
Brought to you by:
theller
From: Marcus G. <mag...@gm...> - 2006-12-17 01:34:17
|
I implemented a strange (to me) pythonic/ctypes equivalent of a static variable for a function that iteratively calls a DLL to update a structure (which contains buffers). It appears that my buffer (allocated by python) goes out-of-scope between calls, even though the structure I iterate on contains a pointer to the buffer memory. This seems reasonable, but I wonder: is there a better idiom? Here is a snippet which I hope illustrates the item. Comments and suggestions for improvement appreciated! Marcus def foo(strData, aStruct=None): # 1: This function is called iteratively; we must track pointer changes if aStruct is None: # create our processing structure myStructure = THE_STRUCTURE() # set the initial buffer pointer to NULL; indicates 1st buffer update myStructure.pOldBuffer = None # create the buffer; use ctypes.create_string_buffer for mutable memory blocks tbuf = create_string_buffer('', 100) myStructure.sReturnObject.pBuffer = addressof(tbuf) myStructure.sReturnObject.uiBufferSize = 100 # static variable here... this seems fragile. Is there a better method? If I don't # do this, tbuf goes out-of-scope between function calls and I get exceptions foo.tbuf = tbuf else: # we are iterating; use the existing struct and set the old buffer accordingly myStructure = aStruct myStructure.pOldBuffer = myStructure.sReturnObject.pBuffer # ... some processing ... # the C call cdll.theLibraryCall(byref(myStructure)) # return the structure for analysis, and potentially a future call return myStructure |