温馨提示:这篇文章已超过469天没有更新,请注意相关的内容是否还可用!
摘要:,,使用Java调用C++进行JNI开发时,可以通过Clion工具实现。开发过程中需要生成ddl包和so包。ddl包是Java本地接口的动态链接库,用于Java与C++之间的交互。而so包是共享对象文件,包含了C++编写的函数或方法。通过Clion工具,可以方便地编写、编译和调试C++代码,并生成相应的ddl和so包,实现Java与C++的集成开发。
使用Clion进行JNI开发:Java调用C++,DDL包和SO包生成
一、Java基础代码
编写对应的Java基础代码,暂时忽略关于静态加载DDL文件的部分,后续再与C++代码集成。
package com.chw.gateway; /** * JNI开发示例 */ public class JavaWithCppApplication { static { // 加载C++编写的动态链接库(DLL或SO文件),路径根据实际情况修改 System.load("E:\document\CLionProjects\testDDL2\cmake-build-debug\libtestDDL2.dll"); } // 声明本地方法(native methods) public native int add(int a, int b); public native int sendSty(Student student); public static void main(String[] args) { JavaWithCppApplication obj = new JavaWithCppApplication(); int result = obj.add(3, 5); System.out.println("Result: " + result); Student student = new Student("chw", 3); System.out.println("ID: " + obj.sendSty(student)); } } // 使用Lombok简化Getter、Setter等代码的编写 @Data @AllArgsConstructor public class Student implements Serializable { private String name; private Integer stuId; }
二、生成C++头部文件
使用javah
命令生成对应的C++头部文件,因为C++与Java交互的头部文件相对复杂,初学者建议直接生成,如果类在包内,指定包名;如果类不在包内,直接使用javah 类名
即可。
javah com.chw.gateway.JavaWithCppApplication
生成的C++头部文件如下(JavaWithCppApplication.h):
```c++
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h> /* Header for class com_chw_gateway_JavaWithCppApplication */
#ifndef _Included_com_chw_gateway_JavaWithCppApplication
#define _Included_com_chw_gateway_JavaWithCppApplication
#ifdef __cplusplus
extern "C" {
#endif
* Class: com_chw_gateway_JavaWithCppApplication
* Method: add
* Signature: (II)I
*/
JNIEXPORT int JNICALL Java_com_chw_gateway_JavaWithCppApplication_add
(JNIEnv *, jobject, jint, jint);
* Class: com_chw_gateway_JavaWithCppApplication
* Method: sendSty
* Signature: (Lcom/chw/gateway/Student;)I
*/
JNIEXPORT int JNICALL Java_com_chw_gateway_JavaWithCppApplication_sendSty
(JNIEnv *, jobject, jobject);
#ifdef __cplusplus
#endif
#endif /* _Included_com_chw_gateway_JavaWithCppApplication */
三、使用Clion写C++实现代码
使用Clion创建C++项目,并引入上面生成的C++头部文件,实现对应的方法(JavaWithCppApplication.cpp),注意引入jni.h头文件,可以在Java安装目录下的include文件夹中找到,对于Windows系统,通常位于D:\software\Java\jdk[版本号]\include\
,您提到的图片中的CMakeLists.txt文件是用于配置CMake构建系统的,您可以在其中配置您的C++源代码和库。
CMakeLists.txt示例: 您可以根据实际情况修改路径和源文件列表,添加链接JNI库的指令以确保正确链接,CMakeLists.txt是CMake构建系统使用的配置文件,用于指定如何构建项目,我们配置项目以包含我们的C++源代码文件,并链接到JNI库,这样,当我们运行CMake构建系统时,它将生成一个包含我们的C++代码和JNI接口的共享库(DLL或SO文件),Java代码可以通过System.load()方法加载这个库并调用其中的本地方法,具体配置如下: 您的CMakeLists.txt可能需要根据您的项目结构和需求进行修改,以下是一个基本的示例: 您的CMakeLists.txt文件应该类似于以下内容: 首先指定项目的名称和类型: 然后添加源代码文件和头文件路径: 最后链接JNI库: ```cmake add_executable(testDDL2 JavaWithCppApplication.cpp) set(CMAKE_CXX_STANDARD 14) include_directories(${CMAKE_SOURCE_DIR}/include)
还没有评论,来说两句吧...