SWIG interfacing C library to Python (Creating 'iterable' Python data type from C 'sequence' struct)

后端 未结 4 1288
北海茫月
北海茫月 2020-12-01 15:17

I have written a Python extension for a C library. I have a data structure that looks like this:

typedef struct _mystruct{
   double * clientdata;
   size_t          


        
4条回答
  •  悲哀的现实
    2020-12-01 15:57

    1. Look up using the %typemap swig command. http://www.swig.org/Doc2.0/SWIGDocumentation.html#Typemaps http://www.swig.org/Doc2.0/SWIGDocumentation.html#Typemaps_nn25 The memberin typemap might do what you want. http://www.swig.org/Doc2.0/SWIGDocumentation.html#Typemaps_nn35 I have a typemap that I found in the Python section that allows me to transfer char** data into the C++ as a list of Python strings. I would guess there would be similar functionality.
    2. Also, you can define %pythoncode in your interface inside the struct inside the swig "i" file. This will allow you to add python methods in the object that gets created for the struct. There is another command %addmethod (I think) that allows you to add methods to the struct or a class as well. Then you can create methods for indexing the objects in C++ or C if you want. There are a lot of ways to solve this.

    For an interface I am working on I used a class object that has some methods for accessing the data in my code. Those methods are written in C++. Then I used the %pythoncode directive inside the class inside of the "i" file and created "getitem" and "setitem" methods in Python code that uses the expose C++ methods to make it look like a dictionary style access.

提交回复
热议问题