I have the following scenario:
Function header along with request and response structures:
struct request1 {
int a1;
int b1;
};
struct response1 {
int y1;
int z1;
};
struct request2 {
int a2;
int b2;
};
struct response2 {
int y2;
int z2;
};
int initialize(int type, void *request, void *response)
When the type is passed as 1, the implementation for initialize will assume request1 and response1 structures and similarly request2 and response2 for type 2.
Question Could you help me with a swig interface for the above function?
Constraints:
What I tried: Considering the number of types will be scalable, I thought of maintaining a lean swig interface file. Leave the responsibility to the python user to take care of the typecasting/deepcopy if necessary.
Also, Python user will know which structure to pass as the request along with the type.
My research led me to the following inefficient solution for the interface file:
No typemaps required. You can create the structures and pass them to initialize
with the minimal SWIG interface file. Below I've added an implementation and a little Python code addition to make the interface for the user more simple:
test.h
struct request1 {
int a1;
int b1;
};
struct response1 {
int y1;
int z1;
};
struct request2 {
int a2;
int b2;
};
struct response2 {
int y2;
int z2;
};
int initialize(int type, void *request, void *response);
test.c
#include "test.h"
int initialize(int type, void *request, void *response) {
if(type == 1) {
struct request1* a = request;
struct response1* b = response;
b->y1 = 2 * a->a1;
b->z1 = 2 * a->b1;
} else {
struct request2* a = request;
struct response2* b = response;
b->y2 = 3 * a->a2;
b->z2 = 3 * a->b2;
}
return type;
}
test.i
%module test
%{
#include "test.h"
%}
%include "test.h"
%pythoncode %{
def initialize1(a, b):
req = request1()
req.a1 = a
req.b1 = b
res = response1()
initialize(1, req, res)
return res.y1, res.z1
def initialize2(a, b):
req = request2()
req.a2 = a
req.b2 = b
res = response2()
initialize(2, req, res)
return res.y2, res.z2
%}
Demo:
>>> import test
>>> test.initialize1(2, 3) # using the %pythoncode helpers
(4, 6)
>>> test.initialize2(2, 3)
(6, 9)
>>> rq = test.request1() # using the bare interface
>>> rq.a1 = 2
>>> rq.b1 = 3
>>> rs = test.response1()
>>> test.initialize(1, rq, rs)
1
>>> rs.y1
4
>>> rs.z1
6