15.13 传递NULL结尾的字符串给C函数库

问题

你要写一个扩展模块,需要传递一个NULL结尾的字符串给C函数库。不过,你不是很确定怎样使用Python的Unicode字符串去实现它。

解决方案

许多C函数库包含一些操作NULL结尾的字符串,被声明类型为 char * .考虑如下的C函数,我们用来做演示和测试用的:

  1. void print_chars(char *s) {
  2. while (*s) {
  3. printf("%2x ", (unsigned char) *s);
  4.  
  5. s++;
  6. }
  7. printf("\n");
  8. }

此函数会打印被传进来字符串的每个字符的十六进制表示,这样的话可以很容易的进行调试了。例如:

  1. print_chars("Hello"); // Outputs: 48 65 6c 6c 6f

对于在Python中调用这样的C函数,你有几种选择。首先,你可以通过调用 PyArg_ParseTuple() 并指定”y“转换码来限制它只能操作字节,如下:

  1. static PyObject *py_print_chars(PyObject *self, PyObject *args) {
  2. char *s;
  3.  
  4. if (!PyArg_ParseTuple(args, "y", &s)) {
  5. return NULL;
  6. }
  7. print_chars(s);
  8. Py_RETURN_NONE;
  9. }

结果函数的使用方法如下。仔细观察嵌入了NULL字节的字符串以及Unicode支持是怎样被拒绝的:

  1. >>> print_chars(b'Hello World')
  2. 48 65 6c 6c 6f 20 57 6f 72 6c 64
  3. >>> print_chars(b'Hello\x00World')
  4. Traceback (most recent call last):
  5. File "<stdin>", line 1, in <module>
  6. TypeError: must be bytes without null bytes, not bytes
  7. >>> print_chars('Hello World')
  8. Traceback (most recent call last):
  9. File "<stdin>", line 1, in <module>
  10. TypeError: 'str' does not support the buffer interface
  11. >>>

如果你想传递Unicode字符串,在 PyArg_ParseTuple() 中使用”s“格式码,如下:

  1. static PyObject *py_print_chars(PyObject *self, PyObject *args) {
  2. char *s;
  3.  
  4. if (!PyArg_ParseTuple(args, "s", &s)) {
  5. return NULL;
  6. }
  7. print_chars(s);
  8. Py_RETURN_NONE;
  9. }

当被使用的时候,它会自动将所有字符串转换为以NULL结尾的UTF-8编码。例如:

  1. >>> print_chars('Hello World')
  2. 48 65 6c 6c 6f 20 57 6f 72 6c 64
  3. >>> print_chars('Spicy Jalape\u00f1o') # Note: UTF-8 encoding
  4. 53 70 69 63 79 20 4a 61 6c 61 70 65 c3 b1 6f
  5. >>> print_chars('Hello\x00World')
  6. Traceback (most recent call last):
  7. File "<stdin>", line 1, in <module>
  8. TypeError: must be str without null characters, not str
  9. >>> print_chars(b'Hello World')
  10. Traceback (most recent call last):
  11. File "<stdin>", line 1, in <module>
  12. TypeError: must be str, not bytes
  13. >>>

如果因为某些原因,你要直接使用 PyObject 而不能使用 PyArg_ParseTuple() ,下面的例子向你展示了怎样从字节和字符串对象中检查和提取一个合适的 char 引用:

  1. /* Some Python Object (obtained somehow) */
  2. PyObject *obj;
  3.  
  4. /* Conversion from bytes */
  5. {
  6. char *s;
  7. s = PyBytes_AsString(o);
  8. if (!s) {
  9. return NULL; /* TypeError already raised */
  10. }
  11. print_chars(s);
  12. }
  13.  
  14. /* Conversion to UTF-8 bytes from a string */
  15. {
  16. PyObject *bytes;
  17. char *s;
  18. if (!PyUnicode_Check(obj)) {
  19. PyErr_SetString(PyExc_TypeError, "Expected string");
  20. return NULL;
  21. }
  22. bytes = PyUnicode_AsUTF8String(obj);
  23. s = PyBytes_AsString(bytes);
  24. print_chars(s);
  25. Py_DECREF(bytes);
  26. }

前面两种转换都可以确保是NULL结尾的数据,但是它们并不检查字符串中间是否嵌入了NULL字节。因此,如果这个很重要的话,那你需要自己去做检查了。

讨论

如果可能的话,你应该避免去写一些依赖于NULL结尾的字符串,因为Python并没有这个需要。最好结合使用一个指针和长度值来处理字符串。不过,有时候你必须去处理C语言遗留代码时就没得选择了。

尽管很容易使用,但是很容易忽视的一个问题是在 PyArg_ParseTuple()中使用“s”格式化码会有内存损耗。但你需要使用这种转换的时候,一个UTF-8字符串被创建并永久附加在原始字符串对象上面。如果原始字符串包含非ASCII字符的话,就会导致字符串的尺寸增到一直到被垃圾回收。例如:

  1. >>> import sys
  2. >>> s = 'Spicy Jalape\u00f1o'
  3. >>> sys.getsizeof(s)
  4. 87
  5. >>> print_chars(s) # Passing string
  6. 53 70 69 63 79 20 4a 61 6c 61 70 65 c3 b1 6f
  7. >>> sys.getsizeof(s) # Notice increased size
  8. 103
  9. >>>

如果你在乎这个内存的损耗,你最好重写你的C扩展代码,让它使用 PyUnicode_AsUTF8String() 函数。如下:

  1. static PyObject *py_print_chars(PyObject *self, PyObject *args) {
  2. PyObject *o, *bytes;
  3. char *s;
  4.  
  5. if (!PyArg_ParseTuple(args, "U", &o)) {
  6. return NULL;
  7. }
  8. bytes = PyUnicode_AsUTF8String(o);
  9. s = PyBytes_AsString(bytes);
  10. print_chars(s);
  11. Py_DECREF(bytes);
  12. Py_RETURN_NONE;
  13. }

通过这个修改,一个UTF-8编码的字符串根据需要被创建,然后在使用过后被丢弃。下面是修订后的效果:

  1. >>> import sys
  2. >>> s = 'Spicy Jalape\u00f1o'
  3. >>> sys.getsizeof(s)
  4. 87
  5. >>> print_chars(s)
  6. 53 70 69 63 79 20 4a 61 6c 61 70 65 c3 b1 6f
  7. >>> sys.getsizeof(s)
  8. 87
  9. >>>

如果你试着传递NULL结尾字符串给ctypes包装过的函数,要注意的是ctypes只能允许传递字节,并且它不会检查中间嵌入的NULL字节。例如:

  1. >>> import ctypes
  2. >>> lib = ctypes.cdll.LoadLibrary("./libsample.so")
  3. >>> print_chars = lib.print_chars
  4. >>> print_chars.argtypes = (ctypes.c_char_p,)
  5. >>> print_chars(b'Hello World')
  6. 48 65 6c 6c 6f 20 57 6f 72 6c 64
  7. >>> print_chars(b'Hello\x00World')
  8. 48 65 6c 6c 6f
  9. >>> print_chars('Hello World')
  10. Traceback (most recent call last):
  11. File "<stdin>", line 1, in <module>
  12. ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type
  13. >>>

如果你想传递字符串而不是字节,你需要先执行手动的UTF-8编码。例如:

  1. >>> print_chars('Hello World'.encode('utf-8'))
  2. 48 65 6c 6c 6f 20 57 6f 72 6c 64
  3. >>>

对于其他扩展工具(比如Swig、Cython),在你使用它们传递字符串给C代码时要先好好学习相应的东西了。

原文:

http://python3-cookbook.readthedocs.io/zh_CN/latest/c15/p13_pass_null_terminated_string_to_c_libraries.html