Kotlin/Native尝试

58次阅读

共计 2477 个字符,预计需要花费 7 分钟才能阅读完成。

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
> 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

正文完
 0