Re: Cast void pointer to C struct pointer and access its members?
H C <[email protected]> Tue, 28 Sep 2021 21:36:13 +0800
| Newsgroups | gmane.comp.programming.swig |
|---|---|
| Message-ID | <CAGPGUd-kbgD8zpQ3bvtoC_wmb49ok1J0C9TaD7fkXAkSifhqhQ@mail.gmail.com> |
Good catch Jake! It works. So #1 and #2 are solved. Is there a more elegant way to cast void* into C struct? So that I don't have to update the SWIG interface file for each new struct my header has. Thanks in advance! On Tue, Sep 28, 2021 at 8:37 PM Jake <[email protected]> wrote: > You've passed `Foo*` as `T` when your return type is `T*`, try: > > %template(convert_foo) convert<Foo>; > > -Jake > > On Mon, Sep 27, 2021 at 11:31 PM H C <[email protected]> wrote: > >> Hi, >> >> I have TestCast.i: >> >> %module test_cast >> >> %{ >> #include "TestCast.hpp" >> %} >> >> %include <stdint.i> >> >> %include "TestCast.hpp" >> %template(convert_foo) convert<Foo*>; >> %template(convert_bar) convert<Bar*>; >> >> >> >> and TestCast.hpp: >> >> #include <cstdint> >> #include <iostream> >> >> #pragma pack(1) >> struct Foo { >> uint8_t a; >> char b; >> int32_t c; >> }; >> #pragma pack() >> >> void* get_foo() { >> static Foo foo{1, 'b', 65535}; >> return static_cast<void*>(&foo); >> } >> >> template <typename T> >> T* convert(void* data) noexcept { >> return static_cast<T*>(data); >> } >> >> I managed to cast the void pointer returned by get_foo() to Foo**: >> >>> import test_cast >> >>> foo_void_ptr = test_cast.get_foo() >> >>> print(foo_void_ptr) >> <Swig Object of type 'void *' at 0x7f9613abd990> >> >>> foo_ptr = test_cast.convert_foo(foo_void_ptr) >> >>> print(foo_ptr) >> <Swig Object of type 'Foo **' at 0x7f9613af3f00> >> >> Questions: >> 1. How can I get Foo* instead of Foo**? >> 2. How can I access the member in Foo in python? >> 3. Is there a more elegant way to cast void* into C struct? >> >> Thanks! >> _______________________________________________ >> Swig-user mailing list >> [email protected] >> https://lists.sourceforge.net/lists/listinfo/swig-user >> > _______________________________________________ Swig-user mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/swig-user