Kotlin/Native尝试
在官网看到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")
}
运行结果如下
> 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()
,但依旧提示内存泄漏,也没有异常退出啊。
如果是改成如下方式就不会提示错误了:
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")
}
结果如下:
> 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
类型的变量怎么获得一直无解,难道只能通过继承获得?
然后我在写文章的时候又发现只要这样写就可以了???
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
}
}
结果如下:
> Task :runProgram
run test
BUILD SUCCESSFUL in 8s