Using SWIG with pointer to function in C struct

前端 未结 2 368
长发绾君心
长发绾君心 2020-12-21 10:35

I\'m trying to write a SWIG wrapper for a C library that uses pointers to functions in its structs. I can\'t figure out how to handle structs that contain function pointers

2条回答
  •  失恋的感觉
    2020-12-21 11:19

    I found an answer. If I declare the function pointer as a SWIG "member function", it seems to work as expected:

    %module test
    %{
    
    typedef struct {
      int (*my_func)(int);
    } test_struct;
    
    int add1(int n) { return n+1; }
    
    test_struct *init_test()
    {
        test_struct *t = (test_struct*) malloc(sizeof(test_struct));
        t->my_func = add1;
        return t;
    }
    
    %}
    
    typedef struct {
        int my_func(int);
    } test_struct;
    
    extern test_struct *init_test();
    

    Session:

    $ python
    Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
    [GCC 4.3.3] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import test
    >>> t = test.init_test()
    >>> t.my_func(1)
    2
    

    I was hoping for something that wouldn't require writing any custom SWIG-specific code (I'd prefer to just "%include" my headers without modification), but this will do I guess.

提交回复
热议问题