在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Java 访问 C++ 方法:JavaCPP

2017-2-9 13:06| 发布者: zhangjf| 查看: 679| 评论: 0

摘要: JavaCPP提供了在Java中高效访问本地C++的方法。采用JNI技术实现,支持所有Java实现包括Android系统,Avian 和 RoboVM。 JavaCPP提供了一系列的Annotation将java代码映射到C++代码,并使用一个可执行的jar包将C++代 ...

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

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

Maven:

  1. <dependency>
  2. <groupId>org.bytedeco</groupId>
  3. <artifactId>javacpp</artifactId>
  4. <version>0.11</version>
  5. </dependency>
复制代码

使用方法:

C++:

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

Java:

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

项目主页:http://www.open-open.com/lib/view/home/1436150685989

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-10 00:46

Copyright 2015-2025 djqfx

返回顶部