增加jni 样例测试 #5

Merged
zeekling merged 1 commits from jni into main 2023-12-31 06:55:24 +00:00
6 changed files with 142 additions and 30 deletions

1
.gitignore vendored
View File

@ -47,4 +47,5 @@ replay_pid*
.idea
target
*.o

25
pom.xml
View File

@ -36,4 +36,29 @@
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>exec-maven-plugin</artifactId>
<groupId>org.codehaus.mojo</groupId>
<version>3.1.1</version>
<executions>
<execution>
<id>uncompress</id>
<phase>install</phase>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable>${basedir}/src/main/native/build.sh</executable>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,25 @@
package com.zeekling.cn.jni;
/**
* javac -encoding utf8 -h . JniTest.java
* gcc -I$JAVA_HOME/include -I$JAVA_HOME/include/linux -fPIC -shared jniTestNative.c -o libJniTestNative.so
*/
public class JniTest {
/**
* native关键字,表明这个方法使用java以外的语言实现
*/
public native void say(String something);
static {
//加载jni库so
System.load(JniTest.class.getResource("/libJniTestNative.so").getPath());
}
public static void main(String[] args) {
//运行后控制台打印出 hello world
new JniTest().say("hello world");
}
}

13
src/main/native/build.sh Executable file
View File

@ -0,0 +1,13 @@
#!/usr/bin/env bash
if [ -z "$JAVA_HOME" ]; then
JAVA_HOME="/opt/bisheng-jdk-17.0.3"
fi
echo "$JAVA_HOME"
basedir=$(pwd)
cd "$basedir/src/main/native/"
gcc -I$JAVA_HOME/include -I$JAVA_HOME/include/linux -fPIC -shared jniTestNative.c -o libJniTestNative.so
echo "$(pwd)"
mv libJniTestNative.so ${basedir}/target/classes/

View File

@ -0,0 +1,21 @@
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_zeekling_cn_jni_JniTest */
#ifndef _Included_com_zeekling_cn_jni_JniTest
#define _Included_com_zeekling_cn_jni_JniTest
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_zeekling_cn_jni_JniTest
* Method: say
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_zeekling_cn_jni_JniTest_say
(JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,27 @@
#include "com_zeekling_cn_jni_JniTest.h"
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_zeekling_cn_jni_JniTest
* Method: say
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_zeekling_cn_jni_JniTest_say(JNIEnv* env, jclass cls, jstring j_str) {
const char *c_str = NULL;
char buff[128] = { 0 };
c_str = (*env)->GetStringUTFChars(env, j_str, NULL);
if (c_str == NULL)
{
printf("out of memory.\n");
return NULL;
}
(*env)->ReleaseStringUTFChars(env, j_str, c_str);
printf("Hello,I'm C++,the Java Str is:%s\n", c_str);
sprintf(buff, "hello %s", c_str);
return (*env)->NewStringUTF(env, buff);
}
#ifdef __cplusplus
}
#endif