How to convert CPointer<ByteVar>? to Int Val...
# kotlin-native
l
How to convert CPointer<ByteVar>? to Int Value/ I try it.reinterpret<IntVar>().pointed.value, but did't work
m
there are unsafe casts between
CPointer<T>?
and
Long
available, provided by
.toLong()
and
.toCPointer<T>()
extension methods:
val longValue = ptr.toLong()
val originalPtr = longValue.toCPointer<T>()
l
I think, need to convert the binary value (in CPointer<T>?) to the reverse order byte (from network byte order to local byte order), and then unsafe casts CPointer<T>? to <IntVar>. But I don't understand how Kotlin/Native support binary types.
m
ptr.toLong()
is C
(int)ptr
val.toCPointer<T>
is C
(T*)val
if you want not pointer itself but value it points to, then better do something like
val ipaddr = (ptr[0] << 24) or (ptr[1] << 16) or (ptr[3] << 8) or (ptr[3])
o
What exactly are trying to achieve?
l
I get: val value = PQgetvalue(res, j, i) (value : CPointer<ByteVar>?)
I want (on С lang.): val = ntohl(\*((uint32_t \*) value))
I write on Kotlin: val val = PQgetvalue(res, j, i)?.let { val result = ntohl(it.reinterpret<IntVar>().pointed.value) \n result } ?: 0
or "ntohl(it.reinterpret<IntVar>()[0])"
But I don't get right value
m
*((u32*)value)
is bad idea - not portable, works only on x86 if not aligned on x4 boundary linux kernel have macro
get_unaligned_be32
and similar, implemented by byte reads and shifts.
l
Thank you all for your help! I studied examples EchoServer.kt and other ex. with native C-functions. I use ntohl/htonl functions from package platform.posix.*