Jakub M.
Jakub M.

Reputation: 33827

SWIG, py + C: no attribute under pointer

I have a strange problem with SWIG ( C + python )

In C, I have a function that returns pointer to struct elements_t. I call the functon in python, get the result ( the pointer) but I cannot access the elements of the structure..

typedef struct elements elements_t;
struct elements {
    int nelements;
    // ... other stuff
};

elements_t* get_elements()
{
    elements_t* p;
    // ...
    return p;
}

And in python I do:

r = clibrary.get_elements()
print r
# <Swig Object of type 'elements_t *' at 0xb77029f8>
print r.nelements
# AttributeError: 'SwigPyObject' object has no attribute 'nelements'

So I get the last error that there is no nelements, even though the p points to a proper structure...

Upvotes: 1

Views: 2754

Answers (2)

Nathan Binkert
Nathan Binkert

Reputation: 9124

It's not pretty, but you can always write accessor functions that allow you to work with the pointer.

Upvotes: 0

Mat
Mat

Reputation: 206699

According to the pointers section of the SWIG for Python docs:

The only thing you can't do is dereference the pointer from Python.

You would need to dereference that pointer to access its members. You'll need to write accessor/mutator functions in C to manipulate the struct members.

Upvotes: 2

Related Questions