SWIG typemap 二维数组到 Python 列表

SWIG typemap 2d array to Python list

这是 的下一级。我需要将 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

С++ header

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

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

基于@MarkTolonen 的 我尝试了以下 typemaps 但没有结果。

// %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*>([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(_dim0);
    for (Py_ssize_t i = 0; i < _dim0; ++i) {
        PyList_SET_ITEM($result, i, PyUnicode_FromString([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']