mercredi 10 mai 2023

Python to C, SWIG design pattern for a function with input and output void pointer arguments

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.

I need to come up with a SWIG interface with an appropriate design pattern to call into the initialize function with a request structure and an response structure.

Constraints:

  • No memory is created in C.
  • C code is not modifiable.
  • Preferred that the python user should be unaware of the underlying C interface.

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:

  • Write a typemap to convert the incoming python request object to SWIG pointer using SWIG_ConvertPtr and type cast it as void pointer.
  • But for the output void pointer argument, converting the void pointer into a python object seems impossible without making use of type information.

Please help advise.

Aucun commentaire:

Enregistrer un commentaire