在官網看到Kotlin/Native已經達到1.0 Beta版因而就去嘗試了一下,結果發現坑仍是挺多的。
首先Kotlin/JVM不少庫是用不了的,這個已經猜到了。官網說已經預先導入了 POSIX、 gzip、 OpenGL、 Metal、 Foundation 等不少其餘的庫,而後我就嘗試了下基本的文件讀寫。和C仍是有一點的差異的。以下:函數
fun hello(): String = "Hello, Kotlin/Native!" fun letter() = "abcdefghigklmnopqrstuvwxyz" fun main(args: Array<String>) { val file = fopen("data.txt", "w") fprintf(file, "%s", hello()) fprintf(file, "%s", "\n") fprintf(file, "%s", letter()) fclose(file) println("write finished") val filer = fopen("data.txt", "r") val buf = ByteArray(255) // fscanf(filer, "%s", buf.pin().addressOf(0)) fgets(buf.pin().addressOf(0), 255, filer) fclose(filer) print(buf.stringFromUtf8()) buf.pin().unpin() println("read finished") system("pause") }
運行結果以下ui
> Task :runProgram write finished Hello, Kotlin/Native! read finished Press any key to continue . . . C:\BuildAgent\work\4d622a065c544371\runtime\src\main\cpp\Memory.cpp:1150: runtime assert: Memory leaks found > Task :runProgram FAILED
使人鬱悶的是提示C:\BuildAgent\work\4d622a065c544371\runtime\src\main\cpp\Memory.cpp:1150: runtime assert: Memory leaks found
,雖然調用了buf.pin().unpin()
,但依舊提示內存泄漏,也沒有異常退出啊。線程
若是是改爲以下方式就不會提示錯誤了:code
fun hello(): String = "Hello, Kotlin/Native!" fun letter() = "abcdefghigklmnopqrstuvwxyz" fun main(args: Array<String>) { val file = fopen("data.txt", "w") fprintf(file, "%s", hello()) fprintf(file, "%s", "\n") fprintf(file, "%s", letter()) fclose(file) println("write finished") val filer = fopen("data.txt", "r") val buf = ByteArray(255) // fscanf(filer, "%s", buf.pin().addressOf(0)) // fgets(buf.pin().addressOf(0), 255, filer) // fclose(filer) // print(buf.stringFromUtf8()) // buf.pin().unpin() buf.usePinned { fgets(it.addressOf(0), 255, filer) fclose(filer) print(buf.stringFromUtf8()) } println("read finished") system("pause") }
結果以下:orm
> Task :runProgram write finished Hello, Kotlin/Native! read finished Press any key to continue . . . BUILD SUCCESSFUL in 9s
另外吐槽下,這麼幾行代碼就要9s,是否是太慢了。繼承
隨後又試了下開啓pthread線程,可是pthread_create
函數的第一個參數th: kotlinx.cinterop.CValuesRef<platform.posix.pthread_tVar>
,CValuesRef
類型的變量怎麼得到一直無解,難道只能經過繼承得到?ip
而後我在寫文章的時候又發現只要這樣寫就能夠了???內存
fun main(args: Array<String>) { pthread_create(null, null, test(), null) } typealias func = kotlinx.cinterop.CPointer<kotlinx.cinterop.CFunction<(kotlinx.cinterop.COpaquePointer?) -> kotlinx.cinterop.COpaquePointer?>>? fun test(): func { return staticCFunction<kotlinx.cinterop.COpaquePointer?, kotlinx.cinterop.COpaquePointer?> { println("run test") it } }
結果以下:ci
> Task :runProgram run test BUILD SUCCESSFUL in 8s