0

I would like to have a method in C++ that returns an array of uint8_t, and then using SWIG make the function available in python as a list, something like:

class MyClass
{
uint8_t array_return() {
uint8_t random_array[100];
return random_array;
}
};

and then in Python:

object = MyClass
my_list = object.array_return()

I am quite new to SWIG, and not super proficient in C++, and other issues on stack overflow didn't seem to be working.

How to convert a C++ array to a Python list using SWIG? This answer didn't seem to be working (using std::vector)

Also tried mapping directly in the .i file:

%typemap(out) uint8_t *array_return %{
  $result = PyList_New(100);
  for (int i = 0; i < 100; ++i) {
    PyList_SetItem($result, i, PyFloat_FromDouble($1[i]));
  }
%}

In the end I would always get a SwigPyObject and it would not be subscriptable/iterable

1
  • SWIG is a great project. However if you are only targeting Python, you would usually be better off using pybind11 (and std library types like vector rather than C arrays). Documentation for that project is excellent. Commented Sep 14, 2023 at 14:27

1 Answer 1

0

std::vector has an official SWIG example: https://github.com/swig/swig/tree/master/Examples/python/std_vector

The resulting object will behave the same as a built-in Python list.

When it comes to your example, there is a large number of problems with it, but none related to the typemap itself which is completely correct.

Here it is a correct working version:

%module myarray

%typemap(out) uint8_t *array_return %{
  $result = PyList_New(100);
  for (int i = 0; i < 100; ++i) {
    PyList_SetItem($result, i, PyLong_FromLong($1[i]));
  }
%}

%inline %{
class MyClass
{
  uint8_t random_array[100];
public:
  uint8_t *array_return() {
    return random_array;
  }
};
%}

Python test:

import myarray
o = myarray.MyClass()
print(o.array_return())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.