我试图从我的Python代码中调用C ++函数,如果我传递一个布尔值或int
它可以完美地工作,但是如果我发送一个字符串,它只会打印第一个字符。
我正在编译:
g++ -c -fPIC foo.cpp -Wextra -Wall -o foo.o
g++ -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o
python3 fooWrapper.py
这是C ++和Python代码:
蟒蛇:
from ctypes import cdll
lib = cdll.LoadLibrary("./libfoo.so")
lib.Foo_bar("hello")
C ++:
#include <iostream>
#include <string>
#include <unistd.h>
void bar(char* string){
printf("%s", string);
}
extern "C" {
void Foo_bar(char* aString){
bar(aString);
}
}
我知道该Boost
库,但是我无法下载它,这种方式除了字符串外效果很好。谢谢您的帮助
问题是字符串在Python 3中作为指向wchar_t
宽字符的指针传递。在little-endian系统中,您的字符串可以用二进制编码为
"h\0\0\0e\0\0\0l\0\0\0l\0\0\0o\0\0\0\0\0\0\0"
当打印时,%s
它将在第一个空终止符处停止。
对于UTF-8编码的字节字符串(char *
),需要一个bytes
object。例如:
lib.Foo_bar("hello".encode())
或使用字节字面量:
lib.Foo_bar(b"hello")
如果您指定了正确的参数类型,那就更好了:
from ctypes import cdll, c_char_p
foo_bar = cdll.LoadLibrary("./libfoo.so").Foo_bar
foo_bar.argtypes = [c_char_p]
foo_bar(b"hello\n")
foo_bar("hello\n")
运行时将输出以下内容:
hello
Traceback (most recent call last):
File "foo.py", line 5, in <module>
foo_bar("hello\n")
ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type
即,后者使用字符串而不是字符串进行调用bytes
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句