Scala:在JNI方法中创建/使用自定义类型

Scala: Create /use custom types in JNI methods

本文关键字:自定义 类型 创建 JNI 方法 Scala      更新时间:2023-10-16

我有各种Scala原生方法。一些例子:

@native protected def xOpen(): Long
@native protected def flushNative(xServPtr: Long): Unit
@native protected def drawLineNative(xServPtr: Long, winPtr: Long, x1: Int, y1: Int, x2: Int, y2: Int): Unit
@native protected def newGraphicsContextNative(xServPtr: Long, winPtr: Long): Long
//And a couple of the signatures from the C++ file.
extern "C" JNIEXPORT void JNICALL Java_pXClient_XCClass_flushNative(JNIEnv * env, jobject c1, jlong displayPtr)
extern "C" JNIEXPORT jlong JNICALL Java_pXClient_XCClass_newGraphicsContextNative(JNIEnv * env, jobject c1,
    jlong displayPtr, jlong winPtr)

我希望在指针上有更强的打字能力,而不是把它们都当作长传。有没有一种方法可以在这里使用AnyVal类,例如:

class XServPtr(val value: Long) extends AnyVal
class WinPtr(val value: Long) extends AnyVal

我可以向JNI添加自定义类型吗?然后,我可以进行从JNI类型到特定c++指针类型的自定义c++隐式类型转换,并在两端都具有类型安全性。

如果您想在类型中显式,您可以使用类似的东西

type wPtr = Any
type HANDLE = wPtr
type HWND = wPtr
@native def SHGetFolderPath(hwndOwner: HWND, nFolder: Int, hToken: HANDLE, dwFlags: Int, pszPath: Array[Char]): Int

至少,我要试一试:)

编辑:最后我做了一个Scala版本的@585534来做我想做的事。