通过 SWIG 输入 Python 3 个字节到 C char*
Input Python 3 bytes to C char* via SWIG
我正在尝试围绕用 C 编写的 SWT 算法创建一个包装器。
我发现 this post 并且那里的代码在 python 2.7 中完美运行,但是当我尝试从 python 3 中 运行 它时,出现错误:
in method 'swt', argument 1 of type 'char *'
。
据我所知,是因为open(img_filename, 'rb').read()
在python2.7中是returnsstring
类型,而在python3中是bytes
类型。
我尝试用下面的代码修改 ccvwrapper.i
但没有成功
%typemap(in) char, int, int, int {
= PyBytes_AS_STRING();
}
函数header:
int* swt(char *bytes, int array_length, int width, int height);
如何通过 SWIG 将 python3 bytes
传递给该函数?
您使用的多参数类型映射有误。多参数类型映射必须具有具体的参数名称。否则,他们会在不需要的情况下过于贪婪地匹配。要从 Python 获取缓冲区的字节和长度,请使用 PyBytes_AsStringAndSize
.
test.i
%module example
%{
int* swt(char *bytes, int array_length, int width, int height) {
printf("bytes = %s\narray_length = %d\nwidth = %d\nheight = %d\n",
bytes, array_length, width, height);
return NULL;
}
%}
%typemap(in) (char *bytes, int array_length) {
Py_ssize_t len;
PyBytes_AsStringAndSize($input, &, &len);
= (int)len;
}
int* swt(char *bytes, int array_length, int width, int height);
test.py
from example import *
swt(b"Hello World!", 100, 50)
调用示例:
$ swig -python -py3 test.i
$ clang -Wall -Wextra -Wpedantic -I /usr/include/python3.6/ -fPIC -shared test_wrap.c -o _example.so -lpython3.6m
$ python3 test.py
bytes = Hello World!
array_length = 12
width = 100
height = 50
%module example
%begin %{
#define SWIG_PYTHON_STRICT_BYTE_CHAR
%}
int* swt(char *bytes, int array_length, int width, int height);
我正在尝试围绕用 C 编写的 SWT 算法创建一个包装器。
我发现 this post 并且那里的代码在 python 2.7 中完美运行,但是当我尝试从 python 3 中 运行 它时,出现错误:
in method 'swt', argument 1 of type 'char *'
。
据我所知,是因为open(img_filename, 'rb').read()
在python2.7中是returnsstring
类型,而在python3中是bytes
类型。
我尝试用下面的代码修改 ccvwrapper.i
但没有成功
%typemap(in) char, int, int, int {
= PyBytes_AS_STRING();
}
函数header:
int* swt(char *bytes, int array_length, int width, int height);
如何通过 SWIG 将 python3 bytes
传递给该函数?
您使用的多参数类型映射有误。多参数类型映射必须具有具体的参数名称。否则,他们会在不需要的情况下过于贪婪地匹配。要从 Python 获取缓冲区的字节和长度,请使用 PyBytes_AsStringAndSize
.
test.i
%module example
%{
int* swt(char *bytes, int array_length, int width, int height) {
printf("bytes = %s\narray_length = %d\nwidth = %d\nheight = %d\n",
bytes, array_length, width, height);
return NULL;
}
%}
%typemap(in) (char *bytes, int array_length) {
Py_ssize_t len;
PyBytes_AsStringAndSize($input, &, &len);
= (int)len;
}
int* swt(char *bytes, int array_length, int width, int height);
test.py
from example import *
swt(b"Hello World!", 100, 50)
调用示例:
$ swig -python -py3 test.i
$ clang -Wall -Wextra -Wpedantic -I /usr/include/python3.6/ -fPIC -shared test_wrap.c -o _example.so -lpython3.6m
$ python3 test.py
bytes = Hello World!
array_length = 12
width = 100
height = 50
%module example
%begin %{
#define SWIG_PYTHON_STRICT_BYTE_CHAR
%}
int* swt(char *bytes, int array_length, int width, int height);