python - 如何将 uint8_t 从 python 传递到 C?

标签 python c python-2.7 swig

我在下面的 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'

最佳答案

SWIG 不知道 uint8_t 类型是什么。您可以将 typedef unsigned char uint8_t 添加到 SWIG 接口(interface)文件以使其知道。这是一个独立的示例。注意:%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'

关于python - 如何将 uint8_t 从 python 传递到 C?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50048048/

相关文章:

python - 如何在Python中组合积分方程?

c - 在 C 中嵌套

在 Linux 用户模式下退出 init 的正确方法

python - 删除字符串中重复出现的正则表达式 - Python

python - WebDriver异常: Message: chrome not reachable after long time

c - linux中的标准输入是什么意思?

Python LDAP 将属性写入 Active Directory

python - PyQt QtGui.QFileDialog 不工作?

python - 避免 Python 路径中的反斜杠

python - 在 python : How to perform regular expression search on "circular" string