Re: Cast void pointer to C struct pointer and access its members?

Jake <[email protected]> Tue, 28 Sep 2021 08:37:38 -0400
Newsgroups gmane.comp.programming.swig
Message-ID <CAGcO-TZ=XsK+b=Tvdqd-n2WqBNJfAg-dJ5-1eQHRL6dS+5pESQ@mail.gmail.com>
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