https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
kotlin-native
  • r

    roamingthings

    12/29/2019, 1:01 PM
    Hi! I’m a bit confused with the available Gradle-Plugins for Kotlin/Native (multiplatform and native) and hope someone can point me in the right direction. I want to write a library in Kotlin/Native that is only targeted for one platform (native on Raspberry Pi) and should be used by other/independently set up Kotlin/Native projects. Do I use the
    org.jetbrains.kotlin.platform.native
    plugin in for this or do I also use the
    kotlin-multiplatform
    plugin?
    • 1
    • 1
  • s

    StefMa

    12/30/2019, 8:08 AM
    What is the difference between the macOS
    release
    and
    debug
    version? Cause my release version crashes directly but my debug version works. I don’t have add any special “cases” like “on
    release
    do this and
    debug
    do this”… so there should be a difference out of the box, right?
    e
    s
    • 3
    • 7
  • p

    Patrick

    12/30/2019, 9:30 AM
    How do I react to a SIGINT event in Kotlin Native?
    m
    d
    • 3
    • 31
  • n

    nikolaymetchev

    12/30/2019, 6:07 PM
    I am trying to figure out how to pass a reference to an int using kotlin native. I have sample C code
    #include<stdio.h>
    #include<CL/cl.h>
    
    int main(void)
    {
        cl_int err;
        cl_uint numPlatforms;
    
        err = clGetPlatformIDs(0, NULL, &numPlatforms);
        if (CL_SUCCESS == err)
            printf("\nDetected OpenCL platforms: %d", numPlatforms);
        else
            printf("\nError calling clGetPlatformIDs. Error code: %d", err);
    
        return 0;
    }
    Here is what I thought the kotlin equivalent will be:
    fun main() {
        val numOfPlatforms: cl_uint = 0U
        val result = clGetPlatformIDs(0, null, cValuesOf(numOfPlatforms))
        if (CL_SUCCESS == result) {
            println("Detected OpenCL platforms: ${numOfPlatforms}")
        } else {
            println("Error calling clGetPlatformIDs. Error code: $result");
        }
    }
    However it seems that I am not passing the pointer to numOfPlatforms correctly as my program returns 0 instead of the expected value of 2. How do I pass a pointer to a an int using Kotlin native?
    l
    • 2
    • 1
  • n

    nikolaymetchev

    12/30/2019, 6:27 PM
    I got it to work by doing this, It feels like I am still not doing it correctly. Any help would be appreciated.
    fun main() {
        memScoped {
            val pointer = cValuesOf(0U).getPointer(memScope)
            val result = clGetPlatformIDs(0, null, pointer)
            if (CL_SUCCESS == result) {
                println("Detected OpenCL platforms: ${pointer[0]}")
            } else {
                println("Error calling clGetPlatformIDs. Error code: $result");
            }
        }
    }
    n
    m
    • 3
    • 9
  • b

    Brendan Weinstein

    12/31/2019, 1:53 AM
    Can I use the ktor client on a background thread (eg Dispatchers.Default)? I am testing with coroutines 1.3.3-native-mt.
    launch {
                  val response = withContext(Dispatchers.Default) {
                    val client = HttpClient { }
                    val emptyBody = object  : OutgoingContent.NoContent() {
                      override val contentLength: Long = 0
    
                      override fun toString(): String = "EmptyContent"
                    }
                    client.get<String>(body = emptyBody, port = 0, block = {
                      url {
                        takeFrom("<https://api.basebeta.com>")
                        encodedPath = "/rankings"
                      }
                    })
                  }
                  output.send(Action.RankingsLoadedAction(
                    list = emptyList(),
                    diffResult = KDiffUtil.calculateDiff(
                      MItemDiffHelper(
                        oldList = emptyList(),
                        newList = emptyList()
                      )
                    ),
                    fromNetwork = true
                  ))
                }
    This leads to the below error
    kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen <http://io.ktor.utils.io|io.ktor.utils.io>.core.ByteReadPacket@1bb0698
    If I follow the stacktrace further down I see references to
    io.ktor.client.features.HttpCallValidator.Companion
    I've read that we should avoid companion objects being used by multiple threads. My understanding is that companion objects are implemented as singletons in native (static inners on jvm?). My hunch is that the inners of Ktor reference a singleton/companion object initialized on the main thread and that leads to recursive freezing throughout the ktor client object graph. Is there a strategy to avoid this that still allows me to make requests on a background thread? I've seen code examples that use ktor on the main thread. For my aim I'd like to make a request via ktor on a background thread.
    a
    b
    k
    • 4
    • 11
  • s

    saket

    01/01/2020, 12:28 AM
    Lazy question: what's the fastest way to know whether my common dependencies have support for a specific platform?
    d
    • 2
    • 1
  • m

    mbonnin

    01/01/2020, 4:45 PM
    What artifact is
    .freeze()
    in? Is it possible to call
    .freeze()
    from swift by somehow exporting it to a framework?
    b
    • 2
    • 6
  • s

    serebit

    01/02/2020, 2:32 AM
    What's the status of kotlinx.cli? I saw in the K/N release notes for 1.3.60 that it's supposed to be bundled in with the main compiler distribution, but I can't seem to access it from my K/N project.
    d
    • 2
    • 1
  • s

    serebit

    01/02/2020, 2:33 AM
    Also, on another note, why is there a changelog entry for 1.3.70 in K/N master? The commit is assigned to a 1.4.0-dev tag, and there's no 1.3.70 release tag.
    b
    • 2
    • 1
  • p

    Prateek Grover

    01/02/2020, 9:11 AM
    Is there a way to have a callback in Kotlin/Native?
    private suspend fun syncFromNewtork(url: String): Boolean = suspendCoroutine { continuation ->
        val knResponseCallback: KNSyncManagerResponseCallBack = freezeObject(KNSyncManagerResponseCallBack(continuation))
    
        knNetworkBridge.makePostRestRequest(url: url)
    }
    
    class KNSyncManagerResponseCallBack(private val continuation: Continuation<Boolean>): KNResponseCallback {
        override fun onSuccess(response: Any?) {
            continuation.resume(true)
        }
    
        override fun onError(errorResponse: Any?) {
            continuation.resume(false)
        }
    }
    k
    b
    t
    • 4
    • 16
  • b

    Big Chungus

    01/02/2020, 11:42 AM
    Has anyone encountered this issue with other native targets?
    r
    n
    • 3
    • 2
  • f

    fcosta

    01/02/2020, 12:49 PM
    Hey guys, I have a class on main thread that calls an async operation inside of it and have a callback that runs on a different thread on iOS. I tried to change the thread without success with
    dispatch_async(dispatch_get_main_queue()) { /* */ }
    😢 How can I handle the result operation?
    • 1
    • 1
  • m

    mbonnin

    01/02/2020, 8:48 PM
    How fast is compilation in general for you? I'm at ~3min to execute
    linkDebugFrameworkMacosX64
    after changing one string, which slows down development quite a lot. Is that expected, should I buy a bigger machine or am I doing something wrong ?
    d
    k
    +4
    • 7
    • 29
  • a

    alexcouch

    01/02/2020, 11:12 PM
    ld.lld: error: undefined symbol: SnowboyDetectConstructor
    >>> referenced by Types.kt:162 (/mnt/agent/work/4d622a065c544371/Interop/Runtime/src/main/kotlin/kotlinx/cinterop/Types.kt:162)
    >>>               /tmp/konan_temp7723188199372240336/result.o:(snowboy_SnowboyDetectConstructor_wrapper0)
    I'm not exactly sure what to do now. I've looked everywhere. I've dumped the cstubs for the library I'm trying to link and everything seems to be in order. I really don't understand why it says that Types.kt:162 is the one throwing the fit. I looked at that line and its CPointer<T>#getPointer. Not sure if its not able to find information on the types being pointed to in C code or what but I'm kinda at my wits end right now.
    d
    j
    • 3
    • 14
  • m

    Mikołaj Kąkol

    01/03/2020, 7:52 AM
    On iOS I'm getting
    kotlin.IllegalStateException: There is no event loop. Use runBlocking { ... } to start one.
    in my native tests when I try to run something like
    GlobalScope.async { /* any code*/ }.await()
    I'm running that code inside custom
    runBlocking
    implementation for iOS. What is the go to solution? Should I use custom
    scope
    for spawning corutines? How do you test async/await on iOS/native?
    m
    • 2
    • 8
  • b

    Big Chungus

    01/03/2020, 3:07 PM
    what can i use for K/N desktop UI? https://github.com/msink/kotlin-libui kinda works for me, but it's missing styling support
    d
    n
    • 3
    • 2
  • k

    Kris Wong

    01/03/2020, 5:35 PM
    is anyone able to dispatch to a background queue from kotlin? it looks like the lambda that you pass it needs to be frozen?
    k
    • 2
    • 43
  • b

    Brendan Weinstein

    01/03/2020, 6:15 PM
    Started last night
    ./gradlew bundle
    still going this morning
    s
    k
    d
    • 4
    • 18
  • d

    Dominaezzz

    01/04/2020, 4:31 PM
    Is there a way to pass a property reference (basically like a method reference to the getter and setter) to a function? I'd rather not pass in two lambdas.
    j
    • 2
    • 9
  • s

    serebit

    01/04/2020, 6:00 PM
    If a K/N program is running within the
    try
    section of some code, and a SIGINT signal is received, will the
    finally
    block attached to that
    try
    be executed before the program closes?
    d
    • 2
    • 2
  • t

    Thomas

    01/04/2020, 7:55 PM
    Hi, the documentation for iOS symbolication says that the Kotlin framework needs to be static if bitcode is used. (https://github.com/JetBrains/kotlin-native/blob/master/IOS_SYMBOLICATION.md#make-frameworks-static-when-using-rebuild-from-bitcode) My app has bitcode enabled and I am using Firebase for crash reporting. With
    -Xg0
    and
    isStatic = true
    all works fine (I need to download dsym from App Store and upload to Firebase each release). However, I need to build the Kotlin framework as a dynamic framework. (because of iOS app extensions, I can explain if needed). The documentation says the following:
    If rebuilding is performed on App Store side, then 
    .dSYM
     of rebuilt dynamic framework seems discarded and not downloadable from App Store Connect. So in this case it may be required to make the framework static, e.g. with
    Is this really the case? If so, is there a workaround/fix for this while still building as a dynamic framework?
    k
    • 2
    • 4
  • j

    jk2018

    01/05/2020, 2:15 AM
    This may be more of a gradle question, but maybe someone here knows this: I'm working on a little Kotlin Native project which creates a (windows) executable. I'm wondering, if I wanted to create some resource files ( e.g. a text file) to be placed in the program dir, next to the exe file, is there an easy way to do this? Or how is something like this generally done? Adding a new gradle task that depends on the build task and then run that ? ( This doc: https://kotlinlang.org/docs/reference/building-mpp-with-gradle.html talks about "resources" a bunch, would my text file be a resource in that sense or is that something different?)
    s
    • 2
    • 5
  • p

    Patrick

    01/06/2020, 9:03 AM
    I've had a look at the C interop documentation and I was wondering if the
    kotlin.native.initRuntimeIfNeeded()
    function has to be called from. Is it inside the staticCFunction or outside of it? Should I call it at the beginning of the function?
    n
    • 2
    • 5
  • m

    mzgreen

    01/06/2020, 10:23 AM
    I’m trying to do something like this:
    val ref = runOnBackgroundThread {
        while(threadIsAlive) {
            // do some work
            runOnUIThread {
                // refresh UI
            }
            sleep(100) // pause bg thread for 100ms
        }
    }
    
    // at some later point
    ref.cancel() // stop thread
    I can do it on Android and JVM using coroutines like this:
    val job = GlobalScope.async {
        while(isActive) {
            // do some work
            launch(context = Dispatchers.Main) {
                // refresh UI
            }
            delay(100)
        }
    }
    
    // later
    job.cancel()
    but Kotlin Native doesn’t support async coroutines yet. I tried to create my own functions that use iOS dispatchers under the hoods but I’m getting
    illegal attempt to access non-shared <object>
    exceptions which I don’t fully understand. Seems like this is not an easy task. The only sample I was able to find is this: https://github.com/wojtek-kalicinski/sudoku-android/blob/master/libsudoku/src/iosMain/kotlin/me/kalicinski/sudoku/Async.kt but the comments are saying that it’s a hack. Is there a sample that shows how to do it properly?
    j
    • 2
    • 3
  • m

    mzgreen

    01/06/2020, 1:46 PM
    I just read about KN threading model 🤯 Seems like it won’t be as easy as I thought. I have an array which one thread is writing into and other thread is reading from. So I have to somehow pass it between threads
    a
    d
    j
    • 4
    • 14
  • l

    Lulu

    01/07/2020, 10:30 AM
    Can
    AtomicRef
    (common version) leak memory like
    AtomicReference
    (native version)? And if so, how to avoid memory leak given that I write code in common?
    n
    p
    k
    • 4
    • 22
  • b

    Big Chungus

    01/07/2020, 1:01 PM
    What can i use for windows or linux native ui that wouls support styling? I've looked at libui, but that doesn't seem to support styling. It doesn't have to be cross platform
    p
    d
    +2
    • 5
    • 16
  • p

    Patrick

    01/07/2020, 1:30 PM
    Can anyone point me to some resources on how to add an icon to your windows executable?
    d
    j
    • 3
    • 23
  • b

    Big Chungus

    01/07/2020, 5:15 PM
    How could I wrap the following C macro in function at *.def file? Cinterop doesn't pick it up as per https://github.com/JetBrains/kotlin-native/blob/master/INTEROP.md#macros
    #define G_CALLBACK(f)         ((GCallback) (f))
    k
    m
    n
    • 4
    • 33
Powered by Linen
Title
b

Big Chungus

01/07/2020, 5:15 PM
How could I wrap the following C macro in function at *.def file? Cinterop doesn't pick it up as per https://github.com/JetBrains/kotlin-native/blob/master/INTEROP.md#macros
#define G_CALLBACK(f)         ((GCallback) (f))
k

Kris Wong

01/07/2020, 5:18 PM
depends on what types you'd be passing to it
function pointers?
b

Big Chungus

01/07/2020, 5:18 PM
kotlin's
(x,y) -> Unit
So yes, i think those will have to be function pointers
k

Kris Wong

01/07/2020, 5:19 PM
and what type is GCallback?
i assume that's a typealias
b

Big Chungus

01/07/2020, 5:19 PM
// G_CALLBACK() macro is used to cast the callback function pointer
    // to generic void pointer
So generic void pointer if that means anything to you?
k

Kris Wong

01/07/2020, 5:20 PM
interesting
b

Big Chungus

01/07/2020, 5:20 PM
Trying to work with GTK3 😄
k

Kris Wong

01/07/2020, 5:22 PM
https://stackoverflow.com/questions/5579835/c-function-pointer-casting-to-void-pointer
b

Big Chungus

01/07/2020, 5:25 PM
Hmm, not quite there. Essentially what I'm looking for is a C function that takes function pointer, call G_CALLBACK with it and returns void pointer
k

Kris Wong

01/07/2020, 5:25 PM
i'm also curious how the block is translated to C
since it's not just a function pointer
b

Big Chungus

01/07/2020, 5:25 PM
In other works what's the C function signature for a function that takes function pointer and returns void pointer
k

Kris Wong

01/07/2020, 5:28 PM
void* f(void (*a)(int))
b

Big Chungus

01/07/2020, 5:29 PM
what's a and arg?
i mean what's the name of the argument to this function?
k

Kris Wong

01/07/2020, 5:33 PM
a
b

Big Chungus

01/07/2020, 5:39 PM
Next question: how do i convert
() -> Unit
to
CPointer<CFunction<() -> Unit>>
m

msink

01/07/2020, 5:39 PM
In C any pointer is compatible to void pointer, so it is just noop.
k

Kris Wong

01/07/2020, 5:42 PM
converting the lambda to a C type is really the crux of it
m

msink

01/07/2020, 5:43 PM
Converting Kotlin lambda to C callback?
k

Kris Wong

01/07/2020, 5:44 PM
i would probably start by adding a function that accepts
() -> Unit
as an argument, and see how the K/N compiler handles that in the generated bindings
m

msink

01/07/2020, 5:44 PM
Something like this: https://github.com/msink/kotlin-libui/blob/341219207095901358cb8a33bacb1963d44e4d6e/libui/src/nativeMain/kotlin/widgets.kt#L81
k

Kris Wong

01/07/2020, 5:46 PM
https://kotlinlang.org/api/latest/jvm/stdlib/kotlinx.cinterop/static-c-function.html
n

napperley

01/07/2020, 10:51 PM
Martynas - Can you please provide a C example where GCallback is being used? What C function are you trying to use?
There might be a workaround which doesn't require having to deal with the C macro.
As an example in GTK there are many macros for casting pointers. With Kotlin Native the pointer casting can be handled with the
reinterpret
extension function, which comes from the Kotlin Native C Interop library.
b

Big Chungus

01/08/2020, 10:07 AM
I've resolved it with
staticCfunction
and unchecked casts. Everything's working now.
I'm using the following for callbacks:
staticCFunction<(CPointer<GtkWidget>,gpointer) -> Unit>() as GCallback
But it seems reinterpret is more elegant solution
✔️ 1
n

napperley

01/08/2020, 8:42 PM
That line can be made more readable by extracting
(CPointer<GtkWidget>, gpointer) -> Unit>()
into a Type Alias. In many cases the Kotlin compiler can apply type inference to the
reinterpret
function.
View count: 4