使用Python的ctypes模块从Python发送字符串到C++需要您将其解析为c_char_p(char *)。我发现我需要使用python 纯字符串,而不是python unicode字符串。如果我使用unicode字符串,则变量会被覆盖而不是被正确发送。下面是一个例子:如何使用ctypes解析unicode字符串?
C++
void test_function(char * a, char * b, char * c) {
printf("Result: %s %s %s", a, b, c);
}
的Python
... load c++ using ctypes ...
lib.test_function.argtypes = [c_char_p, c_char_p, c_char_p]
lib.test_function(u'x', u'y', u'z')
lib.test_function('x', 'y', 'z')
运行上面Python代码给出标准输出以下:
Result: z z z
Result: x y z
这是为什么,这是一个怪癖的ctypes?如果我可以获取unicode字符串,什么是避免这种怪癖的优雅方法?
谢谢!
这应该在Python 2中工作(并且对我有用)。ctypes使用'ctypes.set_conversion_mode(encoding,errors)'设置的编码隐式地将unicode文本字符串转换为字节字符串。在大多数系统上,这默认为严格的ASCII。在Python 3中,OTOH,ctypes不会自动在字节字符串和文本字符串之间进行转换。 – eryksun 2014-12-04 03:55:38
您使用的是什么Python版本和平台? – eryksun 2014-12-04 03:57:50
我在Python 2.7中使用OSX 10.9。我会看看ctypes转换模式,看看它的设置 - 这可能是我的错误:) – rykardo 2014-12-15 20:04:48