Re: [ctypes-users] how to test null pointer to struct return?
by Marcus Goldfish other posts by this author
Nov 16 2005 3:55PM messages near this date
[ctypes-users] how to test null pointer to struct return?
|
[ctypes-users] 1
Thanks Guillaume! I also found a simple test from a previous post by Thomas
Heller,
http://aspn.activestate.com/ASPN/Mail/Message/ctypes-users/1687142
*"NULL pointers are logically false, and non-null pointers are true.... So
passing them to bool() you get this:"*
So a quick fix for me was:
def isNullPointer(p):
if bool(pMsg) == 0:
return True
else:
return False
Marcus
On 11/16/05, Guillaume Proux <gproux@[...].com> wrote:
>
> I thought the question was not very difficult but after a small experiment
> it is more involved than it could appear.
>
> I made a dummy DLL
>
> --- c code ---
> static const Coord val = { 1,2 };
>
> DLLIMPORT Coord* GetXY (int a)
> {
> if (a)
> return &val;
> else
> return NULL;
> }
> --- end ---
>
> Then experimented with it
>
> >>> os.chdir(r"c:\dev\dummydll")
> >>> from ctypes import *
> >>> class Coord(Structure):
> ... _fields_ = [ ("x",c_int), ("y", c_int)]
> ...
> >>> cdll.ReturnNoneDll.GetXY.restype=POINTER(Coord)
> >>> a = cdll.ReturnNoneDll.GetXY(0)
> >>> a
> <ctypes.LP_Coord object at 0x00C03580>
> >>> a[0]
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> ValueError: NULL pointer access
> >>> a.contents
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> ValueError: NULL pointer access
> >>> cdll.ReturnNoneDll.GetXY.restype=c_long
> >>> a = cdll.ReturnNoneDll.GetXY(0)
> >>> a
> 0
>
> Hum, what would be nice would be to have some kind of wrapper that either
> returns None or return the X,Y coordinates...
> Great because it is easy to do with ctypes
>
> >>> def CheckCoord(c):
> ... if c==0:
> ... return None
> ... res=cast(c,POINTER(Coord)).contents
> ... return (res.x,res.y)
> ...
> >>> cdll.ReturnNoneDll.GetXY.restype = CheckCoord
> >>> cdll.ReturnNoneDll.GetXY(1)
> (1, 2)
> >>> cdll.ReturnNoneDll.GetXY(0)
> >>>
>
> Here you are!
>
> Guillaume
>
>
> On 11/17/05, Marcus Goldfish <magoldfish@[...].com> wrote:
> >
> > I need some help with a ctypes POINTER question. My python module
> > calls a C-dll and receives a pointer to a structure. A (c-code) null
> > pointer
> > indicates no message. How do I test this in ctypes?
> > Thanks!
> > Marcus
> > -- code snippet
> > pMsg = mydll.GetMessage() # pointer to a struct conatining message info
> > # if pMsg == null then no message --> how to test this?
> > # else
> > # process message
> >
>
>
Attachments:
unknown1
unknown2
Thread:
Marcus Goldfish
Marcus Goldfish
|