如何将 uint8_t 从 python 传递给 C?

How to pass uint8_t from python to C?

我在下面的 C 中有方法,有没有办法将 python int 转换为 uint8_t?

我已经尝试了 ctypes.c_uint8(...), numpy.uint8(...), and struct.pack('B', ...), 所有他们抛出 'uint8_t'

类型的参数 1

python代码是通过swig生成的,python部分看起来像

def hello(value):
    return _swigdemo.hello(value)
hello = _swigdemo.hello

def hello2(value):
    return _swigdemo.hello2(value):
hello2 = _swigdemo.hello2

C代码

uint8_t hello(uint8_t value)
{
    return value;
}

uint8_t * hello2(uint8_t *value)
{
    return value;
}

调用下面的方法

import swigdemo
import numpy
import ctypes
import struct

temp = ctypes.c_uint8(5) // or numpy.uint8(5) or struct.pack('B', 5)
swigdemo.hello(temp);

会抛出

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: in method 'hello', argument 1 of type 'uint8_t'

SWIG 不知道 uint8_t 类型是什么。您可以将 typedef unsigned char uint8_t 添加到 SWIG 接口文件以让它知道。这是一个独立的例子。注意:%inline 声明两个源代码并告诉 SWIG 包装它。

%module x

%inline %{
    typedef unsigned char uint8_t;

    uint8_t hello(uint8_t value)
    {
        return value;
    }
%}

演示:

>>> import x
>>> x.hello(5)
5
>>> x.hello(255)
255
>>> x.hello(256)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: in method 'hello', argument 1 of type 'uint8_t'