[Gambas-user] unsigned int datatype for external function

T Lee Davidson t.lee.davidson at gmail.com
Wed Jun 13 15:25:26 CEST 2018


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 ]----
> 


More information about the User mailing list