0

I am trying to call a c++ function from Python using using a wrapper created using Swig.

func.cpp

#include "func.h"
void funcCall(Query* queries[]) {
    queries[0]->key = 4;
    queries[0]->val = 5;
}

func.h

#ifndef TESTPROJECT_FUNC_H
#define TESTPROJECT_FUNC_H

#include "string.h"

#endif //TESTPROJECT_FUNC_H

struct Query {
    int key;
    int val;
};

extern "C" void funcCall(Query* queries[]);

func_w.i

%module func_w
%include <cstring.i>

%{
#include "func.h"
%}

%typemap(in) Query*[] {
    $1 = NULL;
    if (PyList_Check($input)) {
        const size_t size = PyList_Size($input);
        Query* ans[size+1];
        $1 = &ans[0];
        for (int i = 0; i < size; ++i) {
            Query *argp = 0 ;
            const int res = SWIG_ConvertPtr(PyList_GetItem($input, i), (void**)&argp, $*1_descriptor, 0);
            if (!SWIG_IsOK(res)) {
                SWIG_exception_fail(SWIG_ArgError(res), "in method '" "$symname" "', argument " "$argnum"" of type '" "$1_type""'");
            }
            $1[i] = argp;
        }
        $1[size] = NULL;
    }
    else {
        // Raise exception
        SWIG_exception_fail(SWIG_TypeError, "Expected list in $symname");
    }
}

%include "func.h"

test.py

import func_w

if __name__ == '__main__':
    query = func_w.Query()
    func_w.funcCall([query])
    print(">>> ", query.key, query.val)

The above code throws Segmentation fault. I am not sure about the type map but without it it gives "TypeError: in method 'funcCall', argument 1 of type 'Query *[]'" error.

Referred to How to pass list of structs to C in SWIG/Python for interface file

Satya Prakash
  • 35
  • 1
  • 6

0 Answers0