【问题标题】:How to pass uint8_t from python to C?如何将 uint8_t 从 python 传递给 C?
【发布时间】:2018-10-07 10:50:53
【问题描述】:

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

我尝试过 ctypes.c_uint8(...)、numpy.uint8(...) 和 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'

【问题讨论】:

  • 请给我们看一些 Python 代码,最好是 minimal reproducible example,来说明这个错误。不要忘记包含错误的完整回溯。
  • python代码是swig生成的,无法贴出源码。但我会更新帖子。
  • 道歉,用回溯更新了帖子,我怎么称呼它。

标签: python c python-2.7 swig


【解决方案1】:

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'

【讨论】:

    猜你喜欢
    • 2013-07-29
    • 2019-08-22
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多