SWIG typemap 2d array to Python list(SWIG将二维数组类型映射到Python列表)
本文介绍了SWIG将二维数组类型映射到Python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是question的下一个级别。我需要将2D C字符数组强制转换为Python列表。
Python端
device_info = getInfoFromCpp()
print(device_info.angles)
for angle in device_info.angles:
print("Angel: " + angle)
错误
<Swig Object of type 'char (*)[MaxStringLength]' at 0x000000D8B2710330>
Execution error: 'SwigPyObject' object is not iterable
С++标头
struct DeviceInformation {
static const int MaxStringLength= 200;
static const int MaxNumberOfAngles= 5;
char serialNumber[MaxStringLength];
char angles[MaxNumberOfAngles][MaxStringLength];
};
基于@MarkTolonen的answer我尝试了以下类型映射,但没有结果。
// %typemap(out) char*[ANY] %{
// %typemap(out) char (*)[ANY] %{
%typemap(out) char [ANY][ANY] %{
PyObject *pyArray = PyList_New(5);
for (uint8_t i = 0; i < 5; ++i) {
PyObject *pyString = PyString_FromString(reinterpret_cast<char*>($1[i]));
PyList_SetItem(pyArray, i, pyString);
}
$result = pyArray;
%}
推荐答案
您的代码为我工作,但以下是问题注释和工作示例中提到的一些更正:
Test.i
%module test
// This works for any size of 2d char array assuming it contains
// UTF-8-encoded, null-terminated strings (no error checking!)
%typemap(out) char [ANY][ANY] %{
$result = PyList_New($1_dim0);
for (Py_ssize_t i = 0; i < $1_dim0; ++i) {
PyList_SET_ITEM($result, i, PyUnicode_FromString($1[i]));
}
%}
%inline %{
struct DeviceInformation {
static const int MaxStringLength= 200;
static const int MaxNumberOfAngles= 5;
char serialNumber[MaxStringLength];
char angles[MaxNumberOfAngles][MaxStringLength];
};
// test function
DeviceInformation getInfoFromCpp() {
return {"serialnumber",{"angle1","angle2","angle3","angle4","angle5"}};
}
%}
演示:
>>> import test
>>> x=test.getInfoFromCpp()
>>> x.serialNumber
'serialnumber'
>>> x.angles
['angle1', 'angle2', 'angle3', 'angle4', 'angle5']
这篇关于SWIG将二维数组类型映射到Python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:SWIG将二维数组类型映射到Python列表
基础教程推荐
猜你喜欢
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
