From: Bob H. <bh...@co...> - 2012-01-22 16:23:27
|
On 1/22/2012 8:48 AM, Alberto Simões wrote: > %extend { > bool have_word(void) const { > return self->w!=NULL; > }; > } > > but then the compiler claims that w is protected. > > Is there any way to go around this problem? The %extend generates a stand-alone function in the generated code, and that function is provided with an argument (named "self") that is a pointer to an instance of the C++ class. For example: %extend Vector { char * __str__() { static char buffer[100]; sprintf(buffer, "%g %g %g", self->x, self->y, self->z); return buffer; }; }; becomes this in the generated wrapper code: SWIGINTERN char *Vector___str__(Vector *self){ static char buffer[100]; sprintf(buffer, "%g %g %g", self->x, self->y, self->z); return buffer; } As such, all C++ access rules are in force. If the member is declared "private", then you will not be able to access it directly like that. So, you are faced with the rules of encapsulation. You either provide methods for accessing the private data member (e.g., get_word(), set_word(), word_is_null(), etc.), or you re-factor your class' interface so that 'w' is publicly accessible (as in the 'x', 'y' and 'z' data members above). If I must keep a data member private, I will add accessors to the C++ class declaration, but I will hide them from SWIG (so the target environment is unaware of them). For example: ... public: #ifndef SWIG bool word_is_null() const { return w == NULL; } #endif ... Then in your extension: %extend { bool have_word(void) const { return !self->word_is_null(); }; } Another option would be to make the data member public, but keep /it/ hidden from the target environment: ... public: #ifndef SWIG void* w; #endif ... Then your extension code will work as written, and the target environment will not be aware or able to access the data member. But if class instances are to be used internally, you have compromised the access of your class' data members. Render me gone, ||| Bob ^(===)^ ---------------------------------oOO--(_)--OOo--------------------------------- I'm not so good with advice...can I interest you in a sarcastic comment? |