python - 使用 swig 模块时出现类型错误 : in method '...' , 类型 'unsigned char const *' 的参数 1

标签 python swig

考虑一下这个小口 mcve:

示例.h

void init(int width, int height);
void dump(const unsigned char *buffer,int pitch);

示例.c

#include <stdio.h>

void init(int width, int height) {
    printf("Initializing width=%d height=%d", width, height);
}

void dump(const unsigned char *buffer,int pitch) {
    for(int i=0;i<pitch;i++) {
        printf("%d\n", buffer[i]);
    }
}

示例.i

%module example

%{
#include "example.h"
%}

%include "example.h"

setup.py

from distutils.core import setup, Extension


example_module = Extension('_example',
                            sources=['example.i', 'example_wrap.c', 'example.c'],
                            swig_opts = [],
                            include_dirs = ["."],
                           )

setup(name='example',
      version='0.1',
      author="BPL",
      description="""Mcve stackoverflow""",
      ext_modules=[example_module],
      py_modules=["example"]
    )

测试.py

import struct
import example as swig_thing

count = 256
width = 8
height = 4

swig_thing.init(width, height)

for frame in range(count):
    print(f"frame {frame}")

    data = []
    for y in range(height):
        for x in range(width):
            data.append(0x00FF0000)
    _buffer = struct.pack(f'{len(data)}L', *data)
    swig_thing.dump(_buffer, width*4)

如果我运行python setup.py build_ext --inplace,然后尝试运行test.py,我将收到以下错误:

TypeError: in method 'dump', argument 1 of type 'unsigned char const *'

问题,如何避免上述错误?

最佳答案

struct.pack可用于创建字节字符串缓冲区。假设您有四个整数要打包为四个无符号长值(16 字节)。 pack接受一个格式字符串。 '4L'表示以 native 字节序格式打包四个无符号长整型。使用'<4L'对于小端和 '>4L'对于大尾数。

>>> import struct
>>> struct.pack('4L',1,2,3,4) # Direct way.
b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00'

>>> data = [1,2,3,4] # Handle variable length...
>>> struct.pack('{}L'.format(len(data)),*data) 
b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00'

>>> struct.pack(f'{len(data)}L',*data) # Python 3.6+
b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00'

练习生成数据列表😊

根据您的 MCVE,将以下类型映射添加到您的 SWIG 界面以了解 unsigned char * :

示例.i

%module example

%{
#include "example.h"
%}

%typemap(in) (const unsigned char* buffer) (char* buffer, Py_ssize_t length) %{
  if(PyBytes_AsStringAndSize($input,&buffer,&length) == -1)
    SWIG_fail;
  $1 = (unsigned char*)buffer;
%}

%include "example.h"

关于python - 使用 swig 模块时出现类型错误 : in method '...' , 类型 'unsigned char const *' 的参数 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50184720/

相关文章:

python - 如何确保 numpy 数组是二维行向量或列向量?

python - 类型错误 : 'in <string>' requires string as left operand, 不是 QString

c++ - 使用 swig 使 C++ 类看起来像一个 numpy 数组

java - Swig for java,从带有数组成员的c结构生成代理类

python - 如何从 Pandas 数据框中提取单元格

python - nose-gae 环境变量问题

c++ - %Python 接口(interface)的 C++ 库的类型映射

python - SWIG 输入文件和带有 numpy 的 vector 。使用%申请?

arrays - 将 2d numpy 数组传递给 C++ 时出现 TypeError

python - Pandas 使用 numpy 百分位数重采样?