Java 访问 C++ 方法 JavaCPP

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

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

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

[[139194]]

Maven:

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

使用方法:

C++:

#include <string> 
  
namespace LegacyLibrary { 
    class LegacyClass { 
        public
            const std::string& get_property() { return property; } 
            void set_property(const std::string& property) { this->property = property; } 
            std::string property; 
    }; 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

Java:

import org.bytedeco.javacpp.*; 
import org.bytedeco.javacpp.annotation.*; 
  
@Platform(include="LegacyLibrary.h"
@Namespace("LegacyLibrary"
public class LegacyLibrary { 
    public static class LegacyClass extends Pointer { 
        static { Loader.load(); } 
        public LegacyClass() { allocate(); } 
        private native void allocate(); 
  
        // to call the getter and setter functions  
        public native @StdString String get_property(); public native void set_property(String property); 
  
        // to access the member variable directly 
        public native @StdString String property();     public native void property(String property); 
    } 
  
    public static void main(String[] args) { 
        // Pointer objects allocated in Java get deallocated once they become unreachable, 
        // but C++ destructors can still be called in a timely fashion with Pointer.deallocate() 
        LegacyClass l = new LegacyClass(); 
        l.set_property("Hello World!"); 
        System.out.println(l.property()); 
    } 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.

 

责任编辑:王雪燕 来源: 开源中国社区
相关推荐

2010-01-19 10:04:30

C++类

2010-01-18 10:01:48

C++中访问控制

2010-02-03 10:50:33

C++多态

2010-02-02 14:36:08

C++ Cstring

2010-02-03 16:35:45

C++回文

2010-02-02 14:55:35

C++访问控制符

2010-01-11 14:05:01

C++学习方法

2010-01-26 17:35:09

C++栈

2010-01-26 09:50:30

C++接口

2010-01-27 15:54:49

C++实现程序

2010-01-25 13:19:44

C++词法分析

2010-01-18 14:41:52

Visual C++开

2010-02-05 11:23:01

C++声明语法

2010-02-06 10:50:10

C++统计对象个数

2010-01-14 14:27:46

Visual C++访

2010-02-02 09:32:32

C++ typedef

2011-07-13 11:34:58

CC++时间函数

2011-04-08 09:52:44

C++C#DLL

2009-09-09 13:47:38

C++访问SqlCe

2010-02-06 11:19:33

C++获取文件
点赞
收藏

51CTO技术栈公众号