简体   繁体   English

SWIG 类型映射二维数组到 Python 列表

[英]SWIG typemap 2d array to Python list

This is next level of this question .这是这个问题的下一个层次。 I need to cast 2d C char array to Python list.我需要将 2d C 字符数组转换为 Python 列表。

Python side Python侧

device_info = getInfoFromCpp()
print(device_info.angles)
for angle in device_info.angles:
  print("Angel: " + angle)

Error错误

<Swig Object of type 'char (*)[MaxStringLength]' at 0x000000D8B2710330>
Execution error: 'SwigPyObject' object is not iterable

С++ header С++ header

struct DeviceInformation {
  static const int MaxStringLength= 200;
  static const int MaxNumberOfAngles= 5;

  char serialNumber[MaxStringLength];
  char angles[MaxNumberOfAngles][MaxStringLength];
};

Based on @MarkTolonen 's answer I try the following typemaps but no result.根据@MarkTolonen回答,我尝试了以下类型映射,但没有结果。

// %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;
%}

Your code as is worked for me, but here are some corrections as mentioned in the question comments and a working example:您的代码对我有用,但这里是问题评论和工作示例中提到的一些更正:

test.i测试.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"}};
}
%}

Demo:演示:

>>> import test
>>> x=test.getInfoFromCpp()
>>> x.serialNumber
'serialnumber'
>>> x.angles
['angle1', 'angle2', 'angle3', 'angle4', 'angle5']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM