首页 > 解决方案 > 如何通过 JNI 从同步 Java 函数调用异步 rust 函数?

问题描述

我目前正在尝试使用 Rust JNI crate 在 Java 中运行异步函数。我想知道是否有办法foo.async在同步功能下运行异步任务。这是在 Java 中运行异步。所以基本上我需要一个fn来运行一个async fn.

package quest.evo.runtime

import quest.evo.runtime.objects.MainWorker
import java.io.File
import java.io.FileOutputStream

object Library {
    external fun create_main_worker(): MainWorker;

    init {
        val tempDir = File(System.getProperty("java.io.tmpdir"))
        try {
            if (tempDir.exists()) {
                val os = System.getProperty("os.name")
                val extension = if (os.startsWith("Windows")) ".dll" else if (os.startsWith("Mac OS")) ".dylib" else ".so"
                if (tempDir.canWrite()) {
                    val file = File(tempDir, "libevo$extension")
                    file.delete()
                    file.createNewFile()
                    try {
                        Library::class.java.classLoader.getResourceAsStream("libevo$extension").use { inputStream ->
                            FileOutputStream(file.absolutePath).use { outputStream ->
                                val buffer = ByteArray(4096)
                                if (inputStream != null) {
                                    while (true) {
                                        val length = inputStream.read(buffer)
                                        if (length == -1) {
                                            break
                                        }
                                        outputStream.write(buffer, 0, length)
                                    }
                                }
                            }
                        }
                    } catch (ignored: Exception) {
                    }
                    System.load(file.absolutePath)
                } else {
                    println("Cannot write to the temp directory.")
                }
            } else {
                println("Cannot find the temp directory.")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    @JvmStatic
    fun main(args: Array<String>) {
        val test = create_main_worker();
    }
}

标签: javaasynchronousrustasync-await

解决方案


推荐阅读