Hi there - I'm quite new to Python, but I've got a tricky situation and Google doesn't seem to know what to do about it.
I'm writing some code to interface to a library written in C using ctypes (which is very nice, I must say...). The C library is object-orientated, so my Python code has this general structure:
Code:
# initialise ctypes
LIB = ctypes.cdll.LoadLibrary("libname.so")
# a class has this basic skeleton:
class ClassName:
# setup return/argument types for functions this class uses
LIB.class_name_foo.restype = c_void_p
LIB.class_name_foo.argtypes = [c_char_p]
# constructor
def __init__(self):
# use LIB to initialise an instance of this class
LIB.class_name_init()
# destructor
def __del__(self):
# use LIB to destroy the instance
LIB.class_name_free()
Which is all very well in normal use, but I get into trouble at program termination. When the program ends, it seems LIB is no longer around - it's been cleaned up, and when I try to use it, I get "Exception AttributeError: "'NoneType' object has no attribute ..." errors.
Why is LIB being cleaned-up prematurely in the first place - do functions not hold references to the things they'll use?
Ideally, I want a way to mark LIB as the last thing that should be deleted in that module (or even that it shouldn't be deleted at all...) - is that possible? Or is there a way to manually increment the reference counter for LIB?
Or I might be doing something wrong - this seems like the sort of thing a language like Python should really protect you from!