寻找cTypesUnicode处理的“Hello World”(包括Python和C代码)

2024-10-01 04:45:10 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能给我演示一个非常简单的pythonctypes示例,其中包含Unicode字符串包括C代码?

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


Tags: 方法函数字符串代码示例unicodepythonctypespythonunicode
3条回答

未经测试,但我认为这应该行得通。在

s = "inputstring"
mydll.my_c_fcn.restype = c_char_p
result = mydll.my_c_fcn(s)
print result

至于内存管理,我的理解是c代码需要管理它创建的内存。也就是说,它不应该释放输入字符串,但最终需要释放返回字符串。在

from ctypes import *

buffer = create_string_buffer(128)
cdll.msvcrt.strcat(buffer, "blah")
print buffer.value

Note: I understand that the Python code is easy, but what I'm struggling with is the C code. Does it need to free its input string? Will its output string get freed by Python on its behalf?

不,您需要自己手动释放缓冲区。人们通常所做的是立即从缓冲值,然后释放缓冲区。在

Can you post the C code? – mike 2 hours ago

^{pr2}$

这个程序使用ctypes从Python调用^{}。它将ab连接到缓冲区中,缓冲区的长度不足以让a + b + (null terminator)演示更安全的n版本。在

必须传递create_unicode_buffer(),而不是为非常数wchar_t*传递常规的不可变u"unicode string",否则可能会出现分段错误。在

如果需要与之对话的函数返回UCS-2和sizeof(wchar_t) == 4,那么您将无法使用unicode_buffer(),因为它在{}之间转换为Python的内部Unicode表示。在这种情况下,您可以使用result.create_string_buffer()result.decode('UCS2')的组合,或者只创建一个c_short和{}的数组。为了调试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:

^{pr2}$

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

相关问题 更多 >