首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Java中,如何使用Bridj动态调用任何本机函数?

在Java中,如何使用Bridj动态调用任何本机函数?
EN

Stack Overflow用户
提问于 2015-03-25 23:34:06
回答 1查看 1.4K关注 0票数 6

Clojure的用户通常希望尽可能懒惰,并延迟类和对象的创建。本着同样的精神,如果我希望从Java内部调用运行时解析的本机函数,我可以使用com.sun.jna.Function.getFunction("foolibrary", "foofuncname"),它返回一个com.sun.jna.Function,可以是invoked

在Clojure中,如下所示:

代码语言:javascript
复制
(let [f (com.sun.jna.Function/getFunction "c" "printf")]
  (.invoke f Integer (to-array ["Hello World"])))

另一方面,BridJ提供了一个吸引人的性能优势,并声称API更简单,但是,我仍然不清楚如何使用BridJ来执行类似于运行时绑定的JNA示例。有人能示范一下吗?此外,如果可能的话,这种方法是否会对性能造成任何惩罚?否则,它似乎是提前生成Java源文件的唯一解决方案。如果有人能证实这一点,我将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-06 20:43:23

编辑:

在更好地理解了这个问题&专注于"dynamically“(没有预编译)之后,我仍然不愿宣称”它是不可能的“(”不可能“是一个很强的单词/意思是”总是“/”从不“),但是我非常肯定这不是BridJ的标准例程。我可以用Bridj想出一个动态的解决方案,但这很可能依赖于"JNAerator“,而这又取决于"JNA”(您的起始位置)。

最初的答案,描述了“用BridJ动态调用任何本机函数”的“标准例程”(涉及代码生成):

根据https://code.google.com/p/bridj/https://code.google.com/p/bridj/wiki/FAQ,您必须:

  1. 设置一个bridJ项目(java项目+ bridJ依赖项)
  2. 对您的库运行the JNAerator (带有bridJ输出选项)。这将生成Java文件,作为导出函数的“存根/委托”。
  3. 这些“存根”可以被java代码引用/使用,并且(应该)调用您的库。

从“他们的快速启动”中抽取的样本:

原始C++代码:

代码语言:javascript
复制
/// 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代码)

代码语言:javascript
复制
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);
  }
}

希望这能有所帮助!

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29268529

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档