10

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 ?

2
  • Well you could just catch the ValueError, hard to give anymore advice than that with no code or context. Commented Sep 3, 2015 at 22:34
  • No need to post the code, I think you just gave a correct answer to the question :) thanks Commented Sep 3, 2015 at 22:38

2 Answers 2

19

NULL Pointers have a boolean False value, so:

if pointer:
    x = pointer.contents
else:
    print "NULL pointer"

Edited for indentation

Sign up to request clarification or add additional context in comments.

1 Comment

I missed to notice that in the documentation…
-2

Try this: http://pythoncentral.io/python-null-equivalent-none/ and go to "checking if a variable is none"

3 Comments

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.
@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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.