This program uses ctypes
to call wcsncat
from Python. It concatenates a
and b
into a buffer that is not quite long enough for a + b + (null terminator)
to demonstrate the safer n
version of concatenation.
You must pass create_unicode_buffer()
instead of passing a regular immutable u"unicode string"
for non-const wchar_t*
parameters, otherwise you will probably get a segmentation fault.
If the function you need to talk to returns UCS-2 and sizeof(wchar_t) == 4
then you will not be able to use unicode_buffer()
because it converts between wchar_t
to Python's internal Unicode representation. In that case you might be able to use some combination of result.create_string_buffer()
and result.decode('UCS2')
or just create an array of c_short
and u''.join(unichr(c) for c in buffer)
. I had to do that to debug an ODBC driver.
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")
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);
}
Makefile: (ensure the indentation is one tab character, not spaces):
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