- 编写JAVA类org.techshare.performance.NativeDemo.java,声明并调用native方法:
public native int add(int x,int y); public static void main(String[] args) { System.load("/home/user/dev/cplusplus/PerformanceC/performance.so"); NativeDemo bcd = new NativeDemo(); int x =12; int y = 22; System.out.println(bcd.add(x,y)); }
- 通过javah导出头文件(导出文件名为org_techshare_performance_NativeDemo.h):javah -classpath ./ -jni org.techshare.performance.NativeDemo
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class org_techshare_performance_NativeDemo */ #ifndef _Included_org_techshare_performance_NativeDemo #define _Included_org_techshare_performance_NativeDemo #ifdef __cplusplus extern "C" { #endif /* * Class: org_techshare_performance_NativeDemo * Method: add * Signature: (II)I */ JNIEXPORT jint JNICALL Java_org_techshare_performance_NativeDemo_add (JNIEnv *, jobject, jint, jint); #ifdef __cplusplus } #endif #endif
-
创建C工程(可使用CodeBlock作为开发平台)
- 生成头文件org_techshare_performance_NativeDemo.h: File – New – File – C/C++ Header – 填写org_techshare_performance_NativeDemo作为文件名 – 选择项目根目录
- 将第二步生成的文件内容拷贝至新创建的头文件中
- 生成C语言源文件:File – New – File – C/C++ source – org_techshare_performance_NativeDemo – 选择项目根目录
- .C文件中引入项目中创建的头文件
- 实现头文件中声明的方法
#include "org_techshare_performance_NativeDemo.h" #include <stdio.h> JNIEXPORT jint JNICALL Java_org_techshare_performance_NativeDemo_add (JNIEnv *env, jobject obj, jint x, jint y){ printf("Hello C world!\n"); int res = x+y; printf("%d+%d=%d",x,y,res); return res; }
-
编译动态库文件(前提是已安装JDK):gcc -I /opt/jdk8u232-b09/include -I /opt/jdk8u232-b09/include/linux org_techshare_performance_NativeDemo.c -shared -fPIC -o performance.so
-
执行JAVA方法
编译C语言版本动态库
猜你喜欢
转载自blog.csdn.net/calvin555555/article/details/104601124
今日推荐
周排行