I need to process a pointer to get its value via a callback. This is problematic since this pointer is null during the first call. So doing a pointer.contents does ValueError: NULL pointer access. To avoid this, how to check if the pointer is null ?
-
Well you could just catch the ValueError, hard to give anymore advice than that with no code or context.Tim Wakeham– Tim Wakeham2015-09-03 22:34:43 +00:00Commented Sep 3, 2015 at 22:34
-
No need to post the code, I think you just gave a correct answer to the question :) thanksBogey Jammer– Bogey Jammer2015-09-03 22:38:28 +00:00Commented Sep 3, 2015 at 22:38
Add a comment
|
2 Answers
NULL Pointers have a boolean False value, so:
if pointer:
x = pointer.contents
else:
print "NULL pointer"
Edited for indentation
1 Comment
Bogey Jammer
I missed to notice that in the documentation…
Try this: http://pythoncentral.io/python-null-equivalent-none/ and go to "checking if a variable is none"
3 Comments
Bogey Jammer
Actually, the pointer is not None, it's not a common python variable type. The pointer is said null when the pointed value does not exist.
Eryk Sun
@BogeyJammer, except Python doesn't have typed variables. It has names that are bound to objects, like tags. So it's enough to say that a pointer and
None are different types. Note that ctypes will generally convert a None argument to a NULL pointer, and the simple pointer types (i.e. c_void_p, c_char_p, c_wchar_p) convert NULL to None when used as a function restype or as a field in a struct or union.KingRadical
That doesn't work for all cases, though. If you specify a ctype function
restype that is a pointer, and that function returns NULL, ctypes does not convert it to None (because the pointer variable is in your scope, it just happens to point to NULL) - you get a ctypes pointer object, so x is None will always be False.