[ctypes-users] Set errcheck during the call?
Brought to you by:
theller
From: Mark H. <ma...@mi...> - 2006-09-29 18:05:50
|
Ctype's errcheck attribute is a great way to maintain Python's error handling idiom when wrapping foreign libraries. I have a case here for which I want to insure I'm using it most efficiently. That is, I'm looking for a way to avoid the errcheck call on every clean ctypes function call. I though this might be possible as it turns out the C library here has its own error trapping mechanism using callbacks which allows me to regain control under the Py interpreter for a moment. Its not possible to raise an Exception at this point as the C lib demands a good return from the callback or it terminates everything with a C exit(), a behavior I believe is fairly common. Instead I try to set the foreign_func.errcheck = MyErrCheckhandler during the callback. That is, for efficiency, I want to avoid an errcheck call upon every clean call; rather Id like it set only on errors for efficiency. This does not work, so I'm assuming setting errcheck during the call is too late? The code, generally: ------------------------------------------------------------------------------------------- ... #foreign function.errcheck is not set, yet. #Make this ctypes function call which throws an error inside the C library foreign_lib.function() # this callback comes from the library error handling mechanism def foreign_lib_err_handler(..., foreign_func_name, ...) getattr( foreign_lib, foreign_func_name).errcheck = myerrcheck_handler #can not raise Exception here, since foreign lib must have this return code else it does BAD THINGS return library_success_code def myerrcheck_handler( ... ): #this works fine if errcheck is set _before_ the call, not during :-( if foreign_lib.err_flag for == error_thrown: raise CustomLibException( some_err_message) ------------------------------------------------------------------------------------------- And finally, if it is possible to make this 'after the call starts' approach work, it would be nice to reset the errcheck attribute so that it does not trip on future no-error calls. Currently of course it can not be reset to None but only to call ables. Regards, Mark |