Make a C++ class look like a numpy array using swig

Make a C++ class look like a numpy array using swig

By : Justin Farris
Date : November 28 2020, 01:01 AM
I hope this helps you . If n_cols and n_rows are (effectively) immutable, your best course of action is to simply create a real numpy array, giving it m_data as storage and (n_rows, n_cols) as shape. That way you will get all the numpy array facilities without any copying and without having to reimplement them in your own code (which would be a lot of quacking to imitate).
code :

Share : facebook icon twitter icon
Pass simple numpy array to C via SWIG

Pass simple numpy array to C via SWIG

By : bhakti satam
Date : March 29 2020, 07:55 AM
wish of those help You can use numpy.i. Just have a look at http://www.scipy.org/Cookbook/SWIG_NumPy_examples
How to create a wrapper for a Matrix class to Numpy with SWIG?

How to create a wrapper for a Matrix class to Numpy with SWIG?

By : Luram Archanjo
Date : March 29 2020, 07:55 AM
To fix this issue Based on the info you provided, typemaps would work. But my experience as an intermittent SWIG user (typically a couple weeks where I use it a lot then hiatus till next project/phase) is that few people have the time to grok that feature.
In your case I believe SWIG typemaps are more of a convenience than a requirement so I would use one of two approaches:
code :
old_some_func = some_function
def some_function(numpy_array):
    tempMat = Matrix()
    # convert numpy_array to SWIG'd Matrix class
Accessing a int16 array using numpy.i and swig

Accessing a int16 array using numpy.i and swig

By : user3630770
Date : March 29 2020, 07:55 AM
it fixes the issue In this instance numpy.i did not work. The main problem was numpy.i does not support (out) typemaps which in this case was precisely what I needed.
Instead using the command -debug-tmsearch when compiling the swig rtserver.i file. Using the output from the command I was able to determine the defined swig type for RadarParm::lag and what it should be. Here is the code that works.
code :
%typemap(out) int16*[2] {
  int i;
  $result = PyList_New(2);
  for (i = 0; i < 2; i++) {
    PyObject *o = PyInt_FromLong($1[i]);
%apply int16*{lag[2]};
Passing numpy string array to C using Swig

Passing numpy string array to C using Swig

By : bin_ast
Date : March 29 2020, 07:55 AM
This might help you So it is doable, but you need to convert the numpy object array to a list of python strings with a.tolist(). Then you can pass it to the C code with the following tutorial code as a char **
code :
// This tells SWIG to treat char ** as a special case
%typemap(in) char ** {
  /* Check if is a list */
    if (PyList_Check($input)) {
        int size = PyList_Size($input);
        Py_ssize_t i = 0;
        $1 = (char **) malloc((size+1)*sizeof(char *));
        for (i = 0; i < size; i++) {
            PyObject *o = PyList_GetItem($input,i);
            if (PyUnicode_Check(o))
                $1[i] = PyUnicode_AsUTF8(PyList_GetItem($input,i));
            else {
                //PyErr_SetString(PyExc_TypeError,"list must contain strings");
                PyErr_Format(PyExc_TypeError, "list must contain strings. %d/%d element was not string.", i, size);
                return NULL;
        $1[i] = 0;
    } else {
        PyErr_SetString(PyExc_TypeError,"not a list");
        return NULL;

// This cleans up the char ** array we malloc'd before the function call
%typemap(freearg) char ** {
  free((char *) $1);
C++ Array to Numpy with SWIG Problem with TypeError

C++ Array to Numpy with SWIG Problem with TypeError

By : Manjunath Nayak
Date : March 29 2020, 07:55 AM
wish of those help Your typemaps and your declaration of the array_add function are not valid. NumPy arrays always have a size and this has to be communicated to C++. There is quite extensive documentation for the usage of NumPy with SWIG.
Two other things:
code :
int add(int x, int y) { return x + y; }
int sub(int x, int y) { return x - y; }
#include <algorithm>
#include <iostream>

class Example {
    void array_add(int *a, int len_a, int *b, int len_b, int *c, int len_c) {
        int const max = std::max(len_a, std::max(len_b, len_c));
        for (int i = 0; i < max; ++i) {
            c[i] = a[i] + b[i];
%module example
    #include "example.h"

%include "numpy.i"
%init %{

%apply (int *IN_ARRAY1, int DIM1) { (int *a, int len_a), (int *b, int len_b) };
%apply (int *INPLACE_ARRAY1, int DIM1) { (int *c, int len_c) };

%include "example.h"
import example
import numpy as np
E = example.Example()
a = np.array([1,1], dtype=np.int32)
b = np.array([1,1], dtype=np.int32)
c = np.array([1,1], dtype=np.int32)
$ swig -python -c++ example.i
$ clang++ -Wall -Wextra -Wpedantic -I/usr/include/python2.7 -fPIC -shared example_wrap.cxx -o _example.so -lpython2.7
$ python test.py
[2 2]
Related Posts Related Posts :
  • C++ Dynamically Allocated Array; Size set by quantity of user input; Writing to a file;
  • enums to be defined as uint8_t variables in structure
  • C++ Overloaded Constructor issues
  • Fast CSV parser in C++
  • MFC GUI application rewrite - threading, messaging, Document/View, etc. Advice needed
  • How to get frame feed of a video in OpenCV?
  • saving data structure c++ to disk
  • Vector of pointers: some clarification needed
  • scaling a bitmap without losing quality
  • How to evaluate a function directly?
  • QNetworkAccessManager: How to change post data at createRequest function
  • Returning std::move of a local variable
  • Is there a fast linear SVM library with a good C++ interface?
  • What is the purpose of name mangling in C++?
  • C++ Why the void function is not working eventhough I called it?
  • How the pointer and the pointer's adress can share the same memory adress?
  • error C2220: warning treated as error - no 'object' file generated
  • exception of strcpy function in c++ console program
  • How to access USB barcode scanner data directly from USB port using C/C++ without driver
  • Under which circumstances will std::vector.clear() call a destructor?
  • Template partial specialisation and dependent names
  • best way to share data between c codes
  • C++ ignores if statement conditions
  • How to set the argv[ ] to be case-insensitive in a Win32 Console Application?
  • How to fix error "clang: error: linker (via gcc) command failed with exit code 1 (use -v to see invocation)"?
  • C++ How do I print a .txt file verbatim?
  • Creating two dimensional array of class
  • How do I correctly use COMMTIMEOUTS with OVERLAPPED IO mode reading from a Serial port
  • An assert macro which expands to static_assert when possible?
  • How to write a copyconstructor for a class which has HANDLE as a member in win32 c++ application?
  • C++ saving info such as tree in a file
  • Transforming an expression template tree
  • How to overload an operator with multiple parameters like a + b + c?
  • C++ 11 with Raspberry Pi performances
  • Postfix incrementer overloading for nested enumerated types
  • Is there a tidy way of associating metadata with functions in C++
  • QObject::installEventFilter(): Cannot filter events for objects in a different thread
  • LNK2005 error with Zxing C++
  • C++ Doubly Linked List with Pointers: Object of class isn't constructed properly
  • Using a random string generator in c++ constructor
  • What should I use instead of void as one of the alternative types in an variant?
  • C++ return value from multithreads using reference
  • How to connect multiple TCP IP clients to same server port using c++
  • Defaul compiler generates the reference operator (In C++)?
  • Unable to change directory time stamp after using FILE_FLAG_BACKUP_SEMANTICS
  • vector handling displaying output
  • WSAGetLastError returns WSAENOTSOCK - Cause?
  • C++: How to overload pow for user type?
  • C++ using arrays as multidimensional despite initalising it as 1D with pointer
  • How negate std::is_integral for use in tag dispatch?
  • Retrieve serial number from USB memory (Windows environment c++)
  • g++ error: invalid preprocessing directive #INCLUDE
  • C++ What is the std::for_each() function parameter type?
  • C++: Read individual lines from text file, sort words alphabetically
  • Saving 'this' address into a variable
  • c++ command line arguments in ubuntu terminal
  • Convert "Cartesian coordinates" to "polar coordinates with respect to user specified origin"
  • In what order are local scoped objects destructed?
  • How to use SDL_MapRGB with SDL 2.0
  • how compiler and interpreter work in case of array declaration
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org