malat
malat

Reputation: 12504

Portable ctypes.c_char_p for python 2.x and 3.x

From the ctypes documentation of python 2.x, we have:

>>> printf("String '%s', Int %d, Double %f\n", "Hi", 10, 2.2)

And from the ctypes documentation of python 3.x, we have:

>>> printf(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2)

So in one case the argtypes for c_char_p requires a str as input, while in the second case it requires bytes. How should I write my function to handle both python 2.x and 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 )

Upvotes: 0

Views: 1067

Answers (1)

Dunes
Dunes

Reputation: 40713

Those types are equivalent. In C strings are arrays or pointers to the char type (each char represented by one byte). In python 3 the closest data type is bytes. Strings in python 3 are encoded using UTF-8, so each char is not guaranteed to be exactly one byte. Whereas, in python 2 strings are typically encoded using Latin-1 (depends on your locale I believe) -- one char, one byte.

To write code that works regardless of interpreter version you should just write b"your string". This creates a str object in python 2 and a bytes object in python 3. Conversely to guarantee a unicode string use u"your string". This creates a unicode object in python 2 and a str object in python 3.

Upvotes: 1

Related Questions