如何在Scala Repl中加载和使用本机库?

时间:2019-05-13 19:47:00

标签: java scala scala-repl

使用scala repl时,简单调用System.loadLibrary(“ opencv_410”)(以防您尝试加载libopencv_410.so)不会使您能够使用本机库。如果您尝试使用JNI调用创建该类的某个对象,它将告诉您--- java.lang.UnsatisfiedLinkError,就像没有加载任何库一样。

Welcome to Scala 2.12.8 (OpenJDK 64-Bit Server VM, Java 1.8.0_201).
Type in expressions for evaluation. Or try :help.

scala> System.loadLibrary(org.opencv.core.Core.NATIVE_LIBRARY_NAME)

scala> new org.opencv.core.Mat()
java.lang.UnsatisfiedLinkError: org.opencv.core.Mat.n_Mat()J
  at org.opencv.core.Mat.n_Mat(Native Method)
  at org.opencv.core.Mat.<init>(Mat.java:26)
  ... 24 elided

scala> 

没有说明的解决方案。

1 个答案:

答案 0 :(得分:0)

要加载本机库,您应该为类scala.tools.nsc.interpreter.IMain加载它。由于无法从我们的范围访问Runtime类的两个参数方法loadLibrary0,因此我们使用反射来调用它。

Welcome to Scala 2.12.8 (OpenJDK 64-Bit Server VM, Java 1.8.0_201).
Type in expressions for evaluation. Or try :help.

scala> val loadLibrary0 = Runtime.getRuntime.getClass.getDeclaredMethods()(4)
loadLibrary0.setAccessible(true)
loadLibrary0.invoke(Runtime.getRuntime, scala.tools.nsc.interpreter.ILoop.getClass, "opencv_java410")
loadLibrary0: java.lang.reflect.Method = synchronized void java.lang.Runtime.loadLibrary0(java.lang.Class,java.lang.String)

scala> 
scala> res1: Object = null

scala> new org.opencv.core.Mat()
res2: org.opencv.core.Mat = Mat [ 0*0*CV_8UC1, isCont=false, isSubmat=false, nativeObj=0x7f5162f2a1f0, dataAddr=0x0 ]