In Java and using Bridj, how can you dynamically call any native function?

Often Clojure users want to be as lazy as possible and delay the creation of classes and objects. In the same vein, if I want to call a built-in function that is allowed at runtime from Java, I can use com.sun.jna.Function.getFunction("foolibrary", "foofuncname")which returns com.sun.jna.Function, which may be invoked.

In Clojure, it looks like this:

(let [f (com.sun.jna.Function/getFunction "c" "printf")]
  (.invoke f Integer (to-array ["Hello World"])))

BridJ, on the other hand, offers an attractive performance advantage and requires a simplified API, but itโ€™s not yet clear to me how to use BridJ to do something similar to the JNA implementation example. Can anyone demonstrate how? Also, if possible, are there any performance penalties with this approach? Otherwise, it seems that generating the Java source file ahead of time is the only solution. I would appreciate it if someone could confirm this.

+4
source share
1 answer

Edit:

" " ( ), , " " ( "" - /... like "always" / "never" ), , BridJ. Bridj, , , "JNAerator", , , "JNA" ( ).

, " " " BridJ" ( ):

https://code.google.com/p/bridj/ https://code.google.com/p/bridj/wiki/FAQ, :

  • bridJ ( java project + bridJ)
  • JNAerator ( bridJ) . Java, "/" .
  • "" / Java- () .

, " ":

++:

/// exported in test.dll / libtest.so / libtest.dylib
class MyClass {
   public:
      MyClass();
      ~MyClass();
      virtual void virtualMethod(int i, float f);
      void normalMethod(int i);
};
void getSomeCount(int* countOut);
...
void test() {
  int count;
  getSomeCount(&count);
  MyClass t;
  t.virtualMethod(count, 0.5f);
}

+ BridJ:

( Java)

import org.bridj.*;     // C interop and core classes
import org.bridj.ann.*; // annotations
import org.bridj.cpp.*; // C++ runtime
import static org.bridj.Pointer.*; // pointer factories such as allocateInt(), pointerTo(java.nio.Buffer), etc...

@Library("test")
public class TestLibrary {
   static {
      BridJ.register(); // binds all native methods in this class and its subclasses
   }
   public static class MyClass extends CPPObject {
      @Virtual(0) // says virtualMethod is the first virtual method
      public native void virtualMethod(int i);
      public native void normalMethod(int i);
   };
   public static native void getSomeCount(Pointer<Integer> countOut);

   public static void test() {
      Pointer<Integer> pCount = allocateInt();
      getSomeCount(pCount);
      MyClass t = new MyClass();
      t.virtualMethod(pCount.get(), 0.5f);
  }
}

, !

+1

All Articles