在官网看到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