天天看点

Java 访问 C++ 方法 JavaCPP

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

Java 访问 C++ 方法 JavaCPP

maven:

<dependency> 

    <groupid>org.bytedeco</groupid> 

    <artifactid>javacpp</artifactid> 

    <version>0.11</version> 

</dependency> 

使用方法:

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; 

    }; 

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()); 

来源:51cto