寻找ctypes unicode处理的"Hello World"(包括Python和C代码)

mik*_*ike 2 c python ctypes

有人能告诉我一个非常简单的Python ctypes示例涉及包含C代码的 Unicode字符串吗?

比方说,一种获取Python Unicode字符串并将其传递给C函数的方法,该函数将其与自身连接并将其返回给Python,后者将其打印出来.

joe*_*ker 6

该程序用于从Python ctypes调用wcsncat.它连接ab进入一个缓冲区,该缓冲区不够长,a + b + (null terminator)无法演示更安全n的连接版本.

您必须传递create_unicode_buffer()而不是u"unicode string"为非const wchar_t*参数传递常规不可变,否则您可能会遇到分段错误.

如果您需要sizeof(wchar_t) == 4与之交谈的函数返回UCS-2,那么您将无法使用unicode_buffer()它,因为它会在wchar_tPython的内部Unicode表示之间进行转换.在这种情况下,你可能能够使用一些组合result.create_string_buffer()result.decode('UCS2')或只是创建数组c_shortu''.join(unichr(c) for c in buffer).我必须这样做来调试ODBC驱动程序.

example.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")
Run Code Online (Sandbox Code Playgroud)

example.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);
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)