Portable ctypes.c_char_p for python 2.x and 3.x -
from ctypes documentation of python 2.x, have:
>>> printf("string '%s', int %d, double %f\n", "hi", 10, 2.2)
and ctypes documentation of python 3.x, have:
>>> printf(b"string '%s', int %d, double %f\n", b"hi", 10, 2.2)
so in 1 case argtypes c_char_p
requires str
input, while in second case requires bytes
. how should write function handle both python 2.x , python 3.x ?
typical scenario is:
my_c_func.argtypes = [ c_char_p ] if __name__ == '__main__': import sys filename = sys.argv[1]; my_c_func( filename )
those types equivalent. in c strings arrays or pointers char type (each char represented 1 byte). in python 3 closest data type bytes
. strings in python 3 encoded using utf-8, each char not guaranteed 1 byte. whereas, in python 2 strings typically encoded using latin-1 (depends on locale believe) -- 1 char, 1 byte.
to write code works regardless of interpreter version should write b"your string"
. creates str
object in python 2 , bytes
object in python 3. conversely guarantee unicode string use u"your string"
. creates unicode
object in python 2 , str
object in python 3.
Comments
Post a Comment