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