栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java JNI Linux-linux上java调用c使用javacpp

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java JNI Linux-linux上java调用c使用javacpp

使用的技术
  • 使用开源项目Javacpp
  • 项目地址 https://github.com/bytedeco/javacpp
环境配置
  • Centos8
  • OracleJDK+环境变量。jdk下载链接 https://www.oracle.com/technetwork/java/javase/downloads/index.html
  • gcc编译工具,dnf install man-pages 或者 yum install man-pages,输入 gcc -version 出现版本信息即可
使用
  • NativeLibrary.h 中的 C++代码
#include 
#include 
using namespace std;

namespace NativeLibrary {
    class NativeClass {
        public:
            const std::string& get_property() { return property; }
            void set_property(const std::string& property) { this->property = property; cout << "C++ Received :" << property << endl;}
            std::string property;
    };
}
  • NativeLibrary.java 中的Java代码
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;

@Platform(include="NativeLibrary.h")
@Namespace("NativeLibrary")
public class NativeLibrary {
    public static class NativeClass extends Pointer {
        static { Loader.load(); }
        public NativeClass() { 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) {
        NativeClass l = new NativeClass();
        l.set_property("Hello World!");
        System.out.println("From C++:"+l.property());
    }
}
  • 将 javacpp.jar,NativeLibrary.h,NativeLibrary.java 放到同一个目录下

  • 运行命令 java -jar javacpp.jar NativeLibrary.java -exec,出现如下信息

    文件下出现了编译后的.class文件和.so文件

  • 通过 Java -cp 运行,注意指出依赖的Jar包 java -cp .:javacpp.jar NativeLibrary

更多原创 shellfish.top

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/338198.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号