通过 SWIG 将 Python 3 个字节输入到 C char* [英] Input Python 3 bytes to C char* via SWIG

查看:34
本文介绍了通过 SWIG 将 Python 3 个字节输入到 C char*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试围绕用 C 编写的 SWT 算法创建一个包装器.
我找到了 这篇文章 并且那里的代码完美适用python 2.7,但是当我尝试从 python 3 运行它时,出现错误:
在方法'swt'中,'char *'类型的参数1.

Im trying to create a wrapper around SWT algorythm written on C.
I found this post and code from there is perfectly working in python 2.7, but when I am trying to run it from python 3, error emerges:
in method 'swt', argument 1 of type 'char *'.

据我所知,这是因为 open(img_filename, 'rb').read() 在 python 2.7 中返回 string 类型,但在 python 3 中它是 bytes 类型.

As far as I know, it is because open(img_filename, 'rb').read() in python 2.7 returns string type, but in python 3 it is a bytes type.

我试图用下面的代码修改 ccvwrapper.i 但没有成功

I tried to modify ccvwrapper.i with the code below but without success

%typemap(in) char, int, int, int {
     $1 = PyBytes_AS_STRING($1);
}

函数标题:int* swt(char *bytes, int array_length, int width, int height);

如何通过 SWIG 将 python3 bytes 传递给该函数?

How I can pass python3 bytes to that function via SWIG?

推荐答案

您使用的多参数类型映射错误.多参数类型映射必须有具体的参数名称.否则,在不需要的情况下,它们会过于贪婪地匹配.要从 Python 获取字节和缓冲区的长度,请使用 PyBytes_AsStringAndSize.

You are using multi-argument typemaps wrong. Multi-argument typemaps have to have concrete parameter names. Otherwise they'd match too greedily in situations where this is not desired. To get the bytes and the length of the buffer from Python use 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, &$1, &len);
    $2 = (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

这篇关于通过 SWIG 将 Python 3 个字节输入到 C char*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆