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

    ribesg

    10/15/2020, 2:36 PM
    I have a crash when an error occurs outside the main thread and I try to log it to Bugsnag. It crashes when it calls this function https://github.com/bugsnag/bugsnag-cocoa/blob/master/Bugsnag/Payload/BugsnagBreadcrumb.m#L92
    Sans titre
    k
    3 replies · 2 participants
  • n

    ntherning

    10/15/2020, 4:34 PM
    Hi! Are there any docs on how to work with the kotlin native source code? More specifically I would like to make some changes to the runtime C++ code to add some debugging facilities to get more insights into unexpected freezing. Are you guys using CLion for the C++ code? What about the Kotlin code?
    i
    k
    4 replies · 3 participants
  • b

    Bor Monty

    10/18/2020, 9:47 AM
    What led to the decision to have bitwise operations through methods instead of operators?
    g
    1 reply · 2 participants
  • g

    Gieted

    10/18/2020, 2:05 PM
    Hi, what is recommended way to manipulate files on desktop native?
    a
    1 reply · 2 participants
  • u

    Ugi

    10/18/2020, 10:10 PM
    Hey everyone, I need some help with C interop, here is my problem: I want to use this function:
    int sodium_unpad(size_t *unpadded_buflen_p, const unsigned char *buf,
                     size_t padded_buflen, size_t blocksize);
    Which looks like this in kotlin:
    @kotlinx.cinterop.internal.CCall public external fun sodium_unpad(unpadded_buflen_p: kotlinx.cinterop.CValuesRef<platform.posix.size_tVar /* = kotlinx.cinterop.ULongVarOf<kotlin.ULong> */>?, buf: kotlinx.cinterop.CValuesRef<kotlinx.cinterop.UByteVar /* = kotlinx.cinterop.UByteVarOf<kotlin.UByte> */>?, padded_buflen: platform.posix.size_t /* = kotlin.ULong */, blocksize: platform.posix.size_t /* = kotlin.ULong */): <http://kotlin.Int|kotlin.Int> { /* compiled code */ }
    As you can see the first parameter is a pointer to
    size_t
    , I worked around this on 64 bit machines by doing this:
    var newSize = ULongArray(1) { 0UL }
        val newSizePinned = newSize.pin()
        sodium_unpad(
            newSizePinned.addressOf(0),
            paddedDataCopyPinned.toPtr(),
            paddedData.size.convert(),
            blocksize.convert()
        )
    And it works fine on 64bit machines, unfortunately on 32bit machines it doesn't expect ULong, but UInt, and I get the following error:
    LibsodiumUtil.kt: (66, 13): Type mismatch: inferred type is CPointer<ULongVarOf<ULong>> but CValuesRef<size_tVar /* = UIntVarOf<UInt> */>? was expected
    Any clues on how to move forward?
    d
    4 replies · 2 participants
  • g

    Gieted

    10/19/2020, 7:47 AM
    How can I call this pointer functions?
    b
    g
    +1
    16 replies · 4 participants
  • g

    Gieted

    10/19/2020, 8:46 AM
    I've followed this guide: https://kotlinlang.org/docs/reference/mpp-share-on-platforms.html However, IntelliJ can't resolve platform specific packages in my shared module.
    a
    9 replies · 2 participants
  • i

    Iaroslav Postovalov

    10/19/2020, 9:38 AM
    How to debug Kotlin/N. runtime?
    1 reply · 1 participant
  • g

    Gieted

    10/20/2020, 8:44 AM
    Can someone help me with this function? I want to implement
    <http://java.io|java.io>.File#path
    using Windows native apis. However, I'm not sure which arguments I should supply this function with and how to convert resulting
    DWORD
    to Kotlin's
    String
    g
    4 replies · 2 participants
  • a

    Anders

    10/20/2020, 2:23 PM
    I noticed that Kotlin Native workers are not wrapping the lambda execution with
    autoreleasepool
    on Darwin platforms. So any ObjC/Swift code that intentionally/unintentionally runs on Kotlin Native workers are going to leak autorelease references, especially when using with Kotlin Coroutines native-mt. edit: This also seemingly impacts K/N garbage collection, because the wrapper around K/N object reference could be made autorelease references. Should this be filed as a kotlinx-coroutine issue, or a Kotlin YouTrack one?
    m
    3 replies · 2 participants
  • k

    Kris Wong

    10/20/2020, 9:17 PM
    does cinterop generate bindings for obj-c extension functions?
    5 replies · 1 participant
  • m

    Merseyside

    10/21/2020, 4:33 AM
    Hi! HttpErrorStatusCodeException: Could not GET 'https://download-cf.jetbrains.com/kotlin/native/builds/releases/1.4.10/windows/kotlin-native-prebuilt-windows-6.3.zip'. Received status code 403 from server: Forbidden
    e
    l
    4 replies · 3 participants
  • s

    Sachin Maharana

    10/22/2020, 10:07 AM
    Hi. Running kotlinc-natives gives me following error. Any suggestions to fix this:
    kotlinc-native Hello.kt -o hello 
    
    /usr/local/bin/kotlinc-native: line 20: /usr/local/bin/run_konan: No such file or directory
    a
    6 replies · 2 participants
  • j

    James Smith

    10/22/2020, 12:31 PM
    I'm trying to distribute a Kotlin MPP library that depends on iOS project. I've tried to include it as a framework, but that way it's not included in the distribution. Right now I'm trying to include the iOS project statically, and I can see the static lib in the resulting .klib distribution. But in runtime it fails with the following:
    dyld: Library not loaded: @rpath/iOSProject.framework/iOSProject
    Here is cinterops:
    // Path to .def file
    defFile("src/iosMain/cinterop/iOSProject.def")
    
    // Directories for header search (an analogue of the -I<path> compiler option)
    includeDirs("$projectDir/native/iOSProject/iOSProject.framework/Headers")
    Here is def:
    language = Objective-C
    headers = iOSProject.h iOSProject-Swift.h
    staticLibraries = libiOSProject.a
    libraryPaths = ../iOSProject.framework
    Any idea why it happens? Maybe there are alternative ways to include the library?
    a
    a
    7 replies · 3 participants
  • h

    HankG

    10/24/2020, 2:37 PM
    I posted this over in ktor but in case people here may have an answer. I think I have a library version clash going on. I'm using coroutines 1.3.9-native-mt, serialization 1.0.0, and ktor version 1.4.0 or 1.4.1 running the SpaceXAPI code snippet but I get
    Uncaught Kotlin exception: kotlin.IllegalStateException: Cannot execute task because event loop was shut down
    with the CIO client explicitly selected when creating the HttpClient. It's code that works under the JVM though.
    j
    15 replies · 2 participants
  • n

    natario1

    10/24/2020, 4:29 PM
    What happens if an object is converted to its stable address with
    StableRef.create(item).asCPointer().toLong()
    , then it is passed outside of the K/N runtime, then it comes back on another thread and you fetch the item again with something like
    long.toCPointer<CPointed>()?.asStableRef<Item>()
    ? Would you end up with the two `Item`s that point to the same location in memory, and that can be accessed concurrently from the two threads? So overcoming the current memory model. Or would this fail, and if so how?
    s
    2 replies · 2 participants
  • h

    HankG

    10/24/2020, 8:03 PM
    Should I be able to use Okio for file access in Kotlin native? Gradle seems to be unhappy trying to import it in a
    commonMain
    or
    nativeMain
    block.
    g
    m
    6 replies · 3 participants
  • h

    HankG

    10/25/2020, 2:17 PM
    I should have clarified that's a Windows question. On Linux and Mac once the package manager installed libcurl it just worked
    m
    3 replies · 2 participants
  • c

    Christian Sousa

    10/26/2020, 10:43 AM
    Hey guys! On our company, we are developing an SDK using KMP, and on iOS, we have some clients that are afraid of the deprecation of
    UIWebView
    that Apple announced: https://developer.apple.com/news/?id=12232019b Running the following command on our binary
    for framework in Frameworks/*.framework; do
      fname=$(basename $framework .framework)
      echo $fname
      nm $framework/$fname | grep UIWebView
    done
    We get the following output:
    0000000000990190 s __OBJC_LABEL_PROTOCOL_$_UIWebViewDelegate
    00000000009e64a0 d __OBJC_PROTOCOL_$_UIWebViewDelegate
    Which means that our SDK does have references to UIWebViewDelegate, but this is not in use and this is a potential roadblocker for every iOS app integrating the SDK. Also, when trying to upload a sample app we get the warning about the usage of
    UIWebView
    . As far as I can understand, the interop lib includes these references for legacy reasons or something like that. What would be our best solution for this issue? Or are there any plans on removing the
    UIWebView
    from the KMP Lib? Thanks a lot! 🙂
    s
    2 replies · 2 participants
  • d

    darkmoon_uk

    10/27/2020, 6:39 AM
    struct -[ObjC-to-Kotlin]-> CValue<struct> -[Kotlin-to-ObjC]-> struct
    ☝️ 🤔 Is this is gap in K/N interop? On iOS, I'm handling some Obj-C struct types in my business logic. These are represented in Kotlin-land as a
    CValue<MyStruct>
    as per interop documentation. Now I'm passing those values back to the UI layer, they comes back out of Kotlin code into Swift/Obj-C. At this point they are still seen as
    CValue<MyStruct>
    with no apparent means, to retrieve/unwrap the original struct type from it... is this not possible? The documentation is lacking when it comes to explaining how to bridge structs in this direction.
    s
    s
    4 replies · 3 participants
  • o

    Omar Mainegra

    10/27/2020, 4:35 PM
    Hi guys, I'm testing the latest
    1.4.20-dev-3947
    version, which works fine in many of ours projects, but in one of them I'm getting
    e: java.lang.IncompatibleClassChangeError: Found interface org.jetbrains.kotlin.ir.declarations.IrModuleFragment, but class was expected
            at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationLoweringExtension.generate(SerializationLoweringExtension.kt:59)
            at org.jetbrains.kotlin.backend.konan.ToplevelPhasesKt$psiToIrPhase$1$1.invoke(ToplevelPhases.kt:203)
            at org.jetbrains.kotlin.backend.konan.ToplevelPhasesKt$psiToIrPhase$1$1.invoke(ToplevelPhases.kt)
            at org.jetbrains.kotlin.psi2ir.Psi2IrTranslator.generateModuleFragment(Psi2IrTranslator.kt:95)
            at org.jetbrains.kotlin.backend.konan.ToplevelPhasesKt$psiToIrPhase$1.invoke(ToplevelPhases.kt:240)
            at org.jetbrains.kotlin.backend.konan.ToplevelPhasesKt$psiToIrPhase$1.invoke(ToplevelPhases.kt)
            at org.jetbrains.kotlin.backend.common.phaser.PhaseBuildersKt$namedOpUnitPhase$1.invoke(PhaseBuilders.kt:97)
            at org.jetbrains.kotlin.backend.common.phaser.PhaseBuildersKt$namedOpUnitPhase$1.invoke(PhaseBuilders.kt:95)
            at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:94)
            at org.jetbrains.kotlin.backend.common.phaser.CompositePhase.invoke(PhaseBuilders.kt:30)
    It works just fine in
    1.4.20-M2
    and in
    jvm
    and
    js
    targets
    d
    2 replies · 2 participants
  • k

    Kristian Tan

    10/28/2020, 11:30 AM
    Hi, I have created a Kotlin Native project using IntelliJ following this kotlinlang tutorial https://kotlinlang.org/docs/tutorials/native/using-intellij-idea.html When I run the project, though, I am getting this error
    e: java.lang.RuntimeException: Cannot extract archive with dependency: /home/kristian/.konan/cache/target-gcc-toolchain-3-linux-x86-64.tar.gz.
    I'm running the project on a Ubuntu machine, and when I check the directory in the error message I can see that the relevant .tar.gz file is present. Does anyone know what I can do to fix this?
    a
    l
    4 replies · 3 participants
  • a

    Animesh Sahu

    10/28/2020, 1:32 PM
    Where are the docs/reference for
    platform.posix.*
    package?
    k
    g
    6 replies · 3 participants
  • a

    Animesh Sahu

    10/28/2020, 1:33 PM
    And how do you do File/IO in K/Native?
    k
    g
    +3
    15 replies · 6 participants
  • a

    aleksey.tomin

    10/29/2020, 5:45 AM
    How can I look for performance problems on macOS target? kotlin 1.4.10, ktor 1.4.1, coroutines 1.3.9-native-mt-2, serialization 1.0.0 I try to run some logic in different threads by
    val ctx1 = newSingleThreadContext("run1")
    launch(ctx1) {
        run1()
    }
    val ctx2 = newSingleThreadContext("run2")
    launch(ctx2) {
        run2()
    }
    But I’ve found that different logics in different contexts can’t work in same time - when I turn off run2 feature - run1 works faster. How can I run some code (with coroutines support) in another thread? PS: run1 - ktor/curl client, run2 - file operations. PPS: I’ll migrate to serialization 1.0.1 today but (I think) it doesn’t matter.
    n
    2 replies · 2 participants
  • s

    Susheel

    10/29/2020, 11:26 PM
    Is it true that unit-tests in KN need a device to run? I was hoping there's a way to run them on the JVM. Is that possible?
    :no_red: 4
    s
    1 reply · 2 participants
  • s

    saket

    10/30/2020, 6:22 AM
    Is there a reference project for using a Carthage dependency from k/n? I’d like to use objective-git but it’s unfortunately not using cocoapods.
    2 replies · 1 participant
  • r

    ribesg

    10/30/2020, 1:57 PM
    There’s no way I can do that, right? It says there’s a conflicting overload, which I understand, but…
    class MyUITableViewDelegate : NSObject(), UITableViewDelegateProtocol {
    
        companion object : NSObjectMeta(), UITableViewDelegateProtocolMeta
    
        override fun tableView(tableView: UITableView, didSelectRowAtIndexPath: NSIndexPath) {
            // Things
        }
    
        override fun tableView(tableView: UITableView, heightForRowAtNSIndexPath: NSIndexPath): CGFloat =
            UITableViewAutomaticDimension
    
    }
    r
    k
    12 replies · 3 participants
  • v

    v79

    10/30/2020, 5:24 PM
    Writing my first ever KotlinNative test application, following the instructions at https://play.kotlinlang.org/hands-on/Introduction%20to%20Kotlin%20Native/04_AddingInteropToBuild . Not going well as gradle is not recognising compilations.main ('main' is in red). Full source is:
    linuxArm32Hfp("pi") {
            compilations.main {
               cinterops {
                   libcurl
               }
            }
            binaries {
                executable {
                    entryPoint = "main"
                }
            }
        }
    k
    b
    30 replies · 3 participants
  • v

    v79

    11/01/2020, 10:26 AM
    I've been working to get Kotlin/Native to produce a Linux binary (from the curl example project), to run on WSL (Windows Subsystem for Linux). I've finally managed to compile my project, but it's created a KLib file, not a Kexe file. Any ideas?
    b
    62 replies · 2 participants
Powered by Linen
Title
v

v79

11/01/2020, 10:26 AM
I've been working to get Kotlin/Native to produce a Linux binary (from the curl example project), to run on WSL (Windows Subsystem for Linux). I've finally managed to compile my project, but it's created a KLib file, not a Kexe file. Any ideas?
b

Big Chungus

11/01/2020, 10:34 AM
What gradle task did you run?
v

v79

11/01/2020, 11:48 AM
I created a "wsl" target and ran `gradle wslBinaries`:
linuxX64("wsl") {
        compilations { "main" {
            cinterops {
                val libCurl by cinterops.creating {
                    defFile(project.file("src/nativeInterop/cinterop/libcurl.def"))
                    includeDirs("src/nativeInterop/cinterop/")
                }
            }
        }}
        binaries {
            executable {
                entryPoint = "main"
            }
        }
    }
b

Big Chungus

11/01/2020, 11:49 AM
You need to run something like linkWslReleaseExecutable
v

v79

11/01/2020, 11:54 AM
I didn't need to do that with the "hello world" version though.
b

Big Chungus

11/01/2020, 11:55 AM
What platform was your hello world for?
Also link tasks are executed as part of build task so might've invoked them unknowingly
Finally, just to be sure, are you building linux target on linux(wsl)?
v

v79

11/01/2020, 11:57 AM
I am trying to cross-compile, from Windows to WSL, as a first step to working out how to cross-compile from Windows to Raspberry Pi Linux.
b

Big Chungus

11/01/2020, 11:58 AM
You cannot cross compile native targets
☝️ 1
So to get linux binary you have to build it on wsl
v

v79

11/01/2020, 11:58 AM
What does "native" mean then? I did manage to build Hello World for the Pi.
from Windows.
b

Big Chungus

11/01/2020, 11:59 AM
Did you build it on wsl or Windows?
Pi might be an exception then
But sure as hell you need to build on wsl to get linux64 binary
There should be a warning in your gradle output when you try to do that on windows
v

v79

11/01/2020, 12:00 PM
Isn't the whole point of this to build an iOS executable from another platform? So cross compiling?
b

Big Chungus

11/01/2020, 12:00 PM
Nope
➕ 2
You can ever build ios on ios, regardless of technology
Kotlin mpp is like c. Write once, compile everywhere
v

v79

11/01/2020, 12:02 PM
So to realistically write Kotlin Native code for the Pi, I need to code and build it on the Pi.
b

Big Chungus

11/01/2020, 12:03 PM
You might be able to build pi executable on wsl since they're both linux
Not sure why/how you've managed to build hello word for pi on windows
v

v79

11/01/2020, 12:09 PM
plugins {
    kotlin("multiplatform") version "1.4.10"
}
group = "org.liamjd.pi"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}
kotlin {
    val hostOs = System.getProperty("os.name")
    val isMingwX64 = hostOs.startsWith("Windows")
    val nativeTarget = when {
        hostOs == "Mac OS X" -> macosX64("native")
        hostOs == "Linux" -> linuxX64("native")
        isMingwX64 -> mingwX64("native")
        else -> throw GradleException("Host OS is not supported in Kotlin/Native.")
    }

    nativeTarget.apply {
        binaries {
            executable {
                entryPoint = "main"
            }
        }
    }

    linuxArm32Hfp("Pi") {
        binaries {
            executable {
                entryPoint = "main"
            }
        }
    }

    sourceSets {
        val nativeMain by getting
        val nativeTest by getting
    }
}
gradle PiBinaries
with main function in src\PiMain\kotlin\main,kt
b

Big Chungus

11/01/2020, 12:11 PM
Ok, lots of thinks wrong here
First off, your sourceSet is nativeMain, not PiMain. So the main.kt file is ignored
Secondly, with your target setup, you'll only get .exe when building on windows
Oh wait. Ignore sourceSet comment
v

v79

11/01/2020, 12:14 PM
I've actually got the same code in src/nativeMain and src/PiMain as I experiment. It definitely compiled, and build\bin\Pi\releaseExecutable\KNWorld.exe definitely executes on the Pi.
b

Big Chungus

11/01/2020, 12:14 PM
You need to remove nativeMain target as it's jyst confusing you now and has nothing to do with pi target in your setup
Then just run the build on wsl
v

v79

11/01/2020, 12:20 PM
I think I'll focus on the Pi, as that's my real target. Was just using wsl as I thought it would be simpler. A pity IntelliJ doesn't run on arm.
And here's an example of cross-compilation from MacOs to Pi https://github.com/jinqian/kotlin-native-chifoumi

https://www.youtube.com/watch?v=KfdNiMP0emE▾

b

Big Chungus

11/01/2020, 12:26 PM
I see looks like you can compile to pi from any *nix host (this includes wsl)
v

v79

11/01/2020, 1:08 PM
I shall leave you in peace, but here is my "Hello World" repository, cross compiled from Windows (not WSL) to Raspberry Pi. https://github.com/v79/KNWorld
b

Big Chungus

11/01/2020, 1:12 PM
Interesting. Still not sure why you keep nativeTarget
v

v79

11/01/2020, 1:17 PM
every example I've found has a nativeTarget 🙂 , I only delete things when I'm sure I don't need them, but I'm still learning what I do and don't need.
sourceSets
doesn't seem necessary; I've commented them out and it works.
b

Big Chungus

11/01/2020, 1:18 PM
Got it. So you've managed to produce pi executable on windows? (Non .exe)
v

v79

11/01/2020, 1:19 PM
A Pi executable from windows, yes. It's an elf binary file.
b

Big Chungus

11/01/2020, 1:19 PM
Congratz!
v

v79

11/01/2020, 1:21 PM
But next step is to do cinterop, and I thought targeting WSL would make that easier to learn because I could just point my header definitions to files on WSL. And that's where we started; I had a KLib but not a WSL Kexe binary.
b

Big Chungus

11/01/2020, 1:27 PM
There's no kexe for pi
Kexe is windows only
As for cinterop, you can install msys2 on windows to have unix env
v

v79

11/01/2020, 1:29 PM
pi@raspberrypi:~/PiShare $ uname -a
Linux raspberrypi 5.4.72-v7l+ #1356 SMP Thu Oct 22 13:57:51 BST 2020 armv7l GNU/Linux
pi@raspberrypi:~/PiShare $
pi@raspberrypi:~/PiShare $ file KNWorld.kexe
KNWorld.kexe: ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux-armhf.so.3, for GNU/Linux 2.6.32, BuildID[xxHash]=a487af0917a9a720, not stripped
pi@raspberrypi:~/PiShare $ ./KNWorld.kexe
PiMain: Hello, enter your name:
Liam Davison
Your name contains 11 letters
Your name contains 9 unique letters
pi@raspberrypi:~/PiShare $
Definitely an ELF binary .Kexe file!
b

Big Chungus

11/01/2020, 1:30 PM
:mind-blown: i give up 😀
v

v79

11/01/2020, 1:30 PM
You have been very patient with me, thank you!
b

Big Chungus

11/01/2020, 1:30 PM
In any case, if you can run that on pi it's fine (learned something new myself)
As for cinterop, install msys2 and required c libs to allow you to work on windows
You can use this for reference
Have a look at the readme as well
Then make sure the libs are installed on both, wsl & msys2. Develop and test on windows, compile the final executable on wsl (even though you can do that on windows, it's better to compile the final binary on wsl to make sure that your cinterop libraries are linked properly for pi)
Or you can just develop on wsl https://www.how2shout.com/how-to/how-to-install-kali-linux-with-gui-on-wsl-windows-10.html
v

v79

11/01/2020, 1:37 PM
I shall bookmark and read. But WSL will be x64 linux, not ARM won't it?
b

Big Chungus

11/01/2020, 1:38 PM
Correct, but it'll still be linux, so lib conventions and paths will be identical. I've found out that unix and windows (via msys2) cinterop is very different when doing that game of life example I've sent you
v

v79

11/01/2020, 1:39 PM
Definitely a project for after lunch. Thanks again for your help and your patience...
b

Big Chungus

11/01/2020, 1:40 PM
It might work for you on windows or it might not, so just to save yourself some ambiguous errors I strongly recommend compiling final binaries on linux
No worries, needed just as much (if not more) help myself when I first bashed my head at Kotlin Native, so just giving back to the community :)
View count: 16