[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Map C bit-field to Gambas datatype


Le 14/03/2024 à 21:45, T Lee Davidson a écrit :
On 3/14/24 16:12, Jussi Lahtinen wrote:
I suppose for usage in external functions there would be nothing special, just create structure with matching variables. But if you want the memory behaviour in Gambas, then you must implement it by yourself.

Jussi

Thank you for the response, Jussi.

So then, for this structure [https://mongoose.ws/documentation/#struct-mg_connection] (which would be received by a Gambas Sub as an event handler/callback in this example [https://mongoose.ws/documentation/tutorials/http-server/#a-minimal-static-server], I could simply declare the unsigned integers as Integers or even Bytes?

Or, should I declare the connection parameter not as a structure but as a pointer and just pass it along as is, and IF I need to access it's fields use pointer arithmetic based on the SizeOf the datatypes?


A bit field is one or more bits in memory. It's the C compiler that decides which bit of which byte of the structure is associated with the field name.

So you must count the number of bits of -successive- bit fields and divide by 8 to know how many bytes it will take.

BUT... The C compiler can freely decides to reorder the bit fields to minimize the number of possible unused bits in the structure.

There is a compiler directive ("packed" in gcc) that tells it to put the fields in memory exactly in the order they are declared in the structure.

Unless this directive is used (which is usually the case), and as what the compiler actually does is, afaik, not declared anywhere in the executable, the Gambas interpreter cannot know at runtime where a bit field is located in memory.

You will tell me that it is the same thing for normal fields (bytes, integers...). But there is a library named "libffi" (ffi means "foreign function interface") that provide a way to create C structure declaration and access them in a standard way. Alas, this library does not support bit fields.

So you have to check at runtime how the structure is organized in memory, and then access the bit fields with the Gambas bit manipulation function (BTst, BSet...). You must aware that this structure organisation can change if you change the library version, the compiler, the system...

Regards,

--
Benoît Minisini.


Follow-Ups:
Re: Map C bit-field to Gambas datatypeBenoît Minisini <benoit.minisini@xxxxxxxxxxxxxxxx>
Re: Map C bit-field to Gambas datatypeT Lee Davidson <t.lee.davidson@xxxxxxxxx>
References:
Map C bit-field to Gambas datatypeT Lee Davidson <t.lee.davidson@xxxxxxxxx>
Re: Map C bit-field to Gambas datatypeJussi Lahtinen <jussi.lahtinen@xxxxxxxxx>
Re: Map C bit-field to Gambas datatypeT Lee Davidson <t.lee.davidson@xxxxxxxxx>