Java访问C++方法JavaCPP

JavaCPP提供了在Java中高效访问本地C++的方法。采用JNI技术实现,支持所有Java实现包括Android系统,Avian 和 RoboVM。

JavaCPP提供了一系列的Annotation将Java代码映射到C++代码,并使用一个可执行的jar包将C++代码转化为可以从JVM内调用的动态链接库文件。

Maven:

 
 
  1.     org.bytedeco
  2.     javacpp
  3.     0.11

使用方法:

C++:

 
 
  1. #include 
  2.  
  3. namespace LegacyLibrary {
  4.     class LegacyClass {
  5.         public:
  6.             const std::string& get_property() { return property; }
  7.             void set_property(const std::string& property) { this->property = property; }
  8.             std::string property;
  9.     };
  10. }

Java:

 
 
  1. import org.bytedeco.javacpp.*;
  2. import org.bytedeco.javacpp.annotation.*;
  3.  
  4. @Platform(include="LegacyLibrary.h")
  5. @Namespace("LegacyLibrary")
  6. public class LegacyLibrary {
  7.     public static class LegacyClass extends Pointer {
  8.         static { Loader.load(); }
  9.         public LegacyClass() { allocate(); }
  10.         private native void allocate();
  11.  
  12.         // to call the getter and setter functions 
  13.         public native @StdString String get_property(); public native void set_property(String property);
  14.  
  15.         // to access the member variable directly
  16.         public native @StdString String property();     public native void property(String property);
  17.     }
  18.  
  19.     public static void main(String[] args) {
  20.         // Pointer objects allocated in Java get deallocated once they become unreachable,
  21.         // but C++ destructors can still be called in a timely fashion with Pointer.deallocate()
  22.         LegacyClass l = new LegacyClass();
  23.         l.set_property("Hello World!");
  24.         System.out.println(l.property());
  25.     }
  26. }

网站标题:Java访问C++方法JavaCPP
网页URL:http://www.hantingmc.com/qtweb/news41/478741.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联