[Gambas-user] unsigned int datatype for external function

Jussi Lahtinen jussi.lahtinen at gmail.com
Wed Jun 13 20:21:59 CEST 2018


Good summary and rule of thumb. This way you wont get troubles, even when
the actual details are much more complicated.


Jussi

On Wed, Jun 13, 2018 at 4:25 PM, T Lee Davidson <t.lee.davidson at gmail.com>
wrote:

> Okay so, when passing values to and receiving values from an external
> library, the bit width of the datatypes should be matched
> or else undefined behavior or garbage values will result.
>
> For example, if a value stored in a 64-bit wide datatype is passed to an
> external function that expects a 32-bit value, the
> behavior is undefined and could lead to application crash. And, if a
> 32-bit value is returned into a 64-bit datatype, the state
> of the higher 32 bits will be undefined tainting the returned value so
> that it should not be relied upon.
>
>
> --
> Lee
>
>
> On 06/11/2018 07:01 PM, Jussi Lahtinen wrote:
> >
> >     Why not do:
> >
> >     Private Extern TakeAndReturn(value As Integer) As Long In
> "liblibTest"
> >
> >
> > Not sure, maybe you could in some situation read some trash along the
> right answer (32 bits is written to output, but 64 bits
> > are read, what are the rest?). But most certainly the problem would
> arise when trying to read output, which consist of multiple
> > variables (arrays, structures, etc).
> >
> > This would be my way to do the conversion:
> >
> > Public Sub UnsignedIntegerToLong(X As Integer) As Long
> >
> >   If BTst(x, 31) = False Then
> >     Return x
> >   Else
> >     Return CLong(BClr(x, 31)) + 2 ^ 31
> >   Endif
> >
> > End
> >
> > And thus:
> > UnsignedIntegerToLong(-1) = 4294967295
> >
> > Note that my earlier example was one bit off (confusing!), but
> apparently it's not that easy to crash program with one variable.
> > However, the main point still remains. Stick with correct bit number!
> >
> >
> > Jussi
> >
> >
> >
> >
> >
> > ----[ Gambas mailing-list is hosted by https://www.hostsharing.net ]----
> >
>
> ----[ Gambas mailing-list is hosted by https://www.hostsharing.net ]----
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.gambas-basic.org/pipermail/user/attachments/20180613/28528f8c/attachment.html>


More information about the User mailing list