Java 访问 C++ 方法 JavaCPP

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

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

Java 访问 C++ 方法 JavaCPP

Maven:

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

使用方法:

C++:

 
 
  1. #include <string> 
  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.     }; 

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.     } 


来源:51CTO

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值