谁能告诉我一个非常简单的 Python ctypes 示例,涉及 Unicode 字符串包括 C 代码?
例如,一种获取 Python Unicode 字符串并将其传递给 C 函数的方法,该函数将其与自身连接起来并将其返回给打印它的 Python。
最佳答案
此程序使用ctypes
调用wcsncat
来自 Python。它将 a
和 b
连接到一个缓冲区中,该缓冲区的长度不足以让 a + b +(空终止符)
演示更安全的 n
版本的连接。
对于非常量 wchar_t*
参数,您必须传递 create_unicode_buffer()
而不是传递常规的不可变 u"unicode string"
,否则您可能会遇到段错误。
如果您需要与之对话的函数返回 UCS-2 和 sizeof(wchar_t) == 4
那么您将无法使用 unicode_buffer()
因为它在 wchar_t
之间转换为 Python 的内部 Unicode 表示。在这种情况下,您可以使用 result.create_string_buffer()
和 result.decode('UCS2')
的某种组合,或者只是创建一个 c_short 数组
和 u''.join(unichr(c) for c in buffer)
。我必须这样做才能调试 ODBC 驱动程序。
例子.py:
#!/usr/bin/env python
#-*- encoding: utf-8 -*-
import sys
from ctypes import *
example = cdll.LoadLibrary(".libs/libexample.so")
example.its_an_example.restype = c_wchar_p
example.its_an_example.argtypes = (c_wchar_p, c_wchar_p, c_uint)
buf = create_unicode_buffer(19) # writable, unlike u"example".
buf[0] = u"\u0000"
a = u"あがぃいぅ ☃ "
b = u"個人 相命理 網上聯盟"
print example.its_an_example(buf, a, len(buf) - len(buf.value) - 1)
print example.its_an_example(buf, b, len(buf) - len(buf.value) - 1)
print buf.value # you may have to .encode("utf-8") before printing
sys.stdout.write(buf.value.encode("utf-8") + "\n")
例子.c:
#include <stdlib.h>
#include <wchar.h>
wchar_t *its_an_example(wchar_t *dest, const wchar_t *src, size_t n) {
return wcsncat(dest, src, n);
}
Makefile:(确保缩进是一个制表符,而不是空格):
all:
libtool --mode=compile gcc -g -O -c example.c
libtool --mode=link gcc -g -O -o libexample.la example.lo \
-rpath /usr/local/lib
关于python - 寻找ctypes unicode处理的 "Hello World"(包括Python和C代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/890793/