handling return codes from CTYPES

Mike C. Fletcher mcfletch at vrplumber.com
Mon Jan 21 16:14:15 CET 2013


On 13-01-21 05:46 AM, Steve Simmons wrote:

...
> >>> from ctypes import *
> >>> sLib = cdll.slib
> >>> lic_key = c_char_p("asdfghjkl".encode(encoding='utf_8', 
> errors='strict'))
> >>> initResult = sLib.InitScanLib(lic_key.value)
> >>> print("InitScanLib Result:  ", initResult)
> InitScanLib Result:   65535
> >>>
>
> I've tried declaring initResult as c_short by: inserting...
>
> >>> initResult = c_short(0)
>
> ... before the call to sLib.InitScanLib but I still get the same 
> response (65535).
That's because you've just discarded the object you created.

What you wanted was, I believe:

     initScanLib = sLib.InitScanLib
     initScanLib.restype = c_short

     initResult = initScanLib( ... )

i.e. you tell the initScanLib function how to coerce its result-type.  
*Some* C functions take a pointer to a data-value to fill in their data, 
but not *your* function.  That pattern looks like:

     result = c_short(0)
     my_ctypes_function( ..., byref(result) )
     print result.value

i.e. you have to pass the variable into the function (as a 
reference/pointer).

HTH,
Mike

-- 
________________________________________________
   Mike C. Fletcher
   Designer, VR Plumber, Coder
   http://www.vrplumber.com
   http://blog.vrplumber.com




More information about the Python-list mailing list