gpt4 book ai didi

java - Kotlin:创建并引用真正的 Java 数组(针对 JNA)

转载 作者:行者123 更新时间:2023-11-30 08:07:01 25 4
gpt4 key购买 nike

我正在尝试将 JNA 与 Kotlin 结合使用,但遇到了问题。 引起:java.lang.IllegalArgumentException:类[Lcom.sun.jna.platform.win32.WinDef$HMODULE;不是受支持的参数类型(在类 kotmem.unsafe.Psapi 的方法 EnumProcessModulesEx 中)

我的Psapi直接映射对象:

package kotmem.unsafe

import com.sun.jna.*
import com.sun.jna.platform.win32.*
import com.sun.jna.ptr.*

object Psapi {

// note Array<WinDef.HMODULE?>
external fun EnumProcessModulesEx(process: Pointer, modules: Array<WinDef.HMODULE?>, cb: Int,
neededModules: IntByReference, flags: Int): Boolean

external fun GetModuleInformation(process: Pointer, module: WinDef.HMODULE, moduleInfo: LPMODULEINFO, cb: Int): Boolean

external fun GetModuleBaseNameA(process: Pointer, module: WinDef.HMODULE, fileName: ByteArray, size: Int): Int

init {
Native.register(NativeLibrary.getInstance("Psapi"))
}

}

问题似乎出在我的调用方式上。 JNA 不喜欢我假设的 Kotlin 的 Array 类,因为它不知道如何映射此类。有没有办法引用真正的 Java 数组,以便 JNA 可以映射此函数?另外,有没有办法构造这样的?

我是这样调用它的:

fun modulesOfProcess(process: UnsafeProcess): List<UnsafeModule> {
val list = emptyList<UnsafeModule>()

val process = process.handle.pointer

// note that I construct using arrayOfNulls
val modules = arrayOfNulls<WinDef.HMODULE>(1024)
val needed = IntByReference()

Psapi.EnumProcessModulesEx(process, modules, modules.size, needed, 1)

for (i in 0..needed.value / 4) {
val module = modules[i] ?: continue
val info = LPMODULEINFO()
if (!Psapi.GetModuleInformation(process, module, info, info.size()))
list + UnsafeModule(module, info)
}

return list
}

最佳答案

直接映射不支持 Pointer 数组或 NativeMapped 数组 ( see docs )。

您可以手动构造一个指针缓冲区并传递它:

Pointer modules = new Memory(Pointer.SIZE * length);
int offset = 0;
for (h: hmodules) {
modules.setPointer(Pointer.SIZE * offset, h.getPointer())
offset += 1;
}

关于java - Kotlin:创建并引用真正的 Java 数组(针对 JNA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33950973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com