繁体   English   中英

什么是Python3的const char *

[英]What is const char* for Python3

C语言中的函数如下:

char* test(const char* input, size_t length);

使用swig(3.0.2)导出到python扩展名。

在python2中,运行test("hello",len("hello")) ,该函数运行良好。

但是在python 3中,运行config="hello";test(config.encode("utf-8"),len(config.encode("utf-8")))

TypeError: in method 'test', argument 0 of type 'char const *'

如何在Python3中使用此功能?

我找出真正的原因。

在python 3中,我应该使用与python2中相同的东西。 也就是说test("hello",len("hello"))

但是Python3的len(“ hello”)不适用于真正的UTF-8。

例如,

python2:

>>>len("测试")
4

python3:

>>>len("测试")
2

因此,C函数的长度错误。

在C中, const char *不可变 char * (字符串)的类型。 我不确定为什么会收到该错误-可能是因为您传递的是可变的Python字符串-您可以修改/重新分配它:

config = "hello"
config = config[:2]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM