jni 开发

2月 27, 2023 |

jni 开发

生成jni头文件

java9之后没有javah, 取而代之的是javac -h 选项,maven 配置如下

      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <compilerArgs>
            <arg>-h</arg>
            <arg>target/headers</arg>
          </compilerArgs>
          <source>11</source>
          <target>11</target>
        </configuration>
      </plugin>

C代码示例

  JNIEXPORT jclass JNICALL Java_cn_javacoder_YunsiClassLoader_defineClassJni
  (JNIEnv *env, jclass clazz, jobject loader, jstring name, jbyteArray buf, jint offset, jint len, jobject pd, jstring source) {
	//jbyteArray to jbyte
    jbyte*  nativeByte = (*env)->GetByteArrayElements(env, buf, 0);
	 //jbyte 写回jbyteArray
    (*env)->ReleaseByteArrayElements(env, buf, nativeByte, 0);
    jclass loaderClass = (*env)->GetObjectClass(env, loader);
    jmethodID defineClass1 = (*env)->GetStaticMethodID(env, loaderClass, "defineClass1",
         "(Ljava/lang/ClassLoader;Ljava/lang/String;[BIILjava/security/ProtectionDomain;Ljava/lang/String;)Ljava/lang/Class;");
    jobject ret = (*env)->CallStaticObjectMethod(env, loaderClass, defineClass1, loader, name, buf, offset, len, pd, source);
    return (jclass)ret;
  }

编译

gcc -fPIC -shared -o libxyz.so -I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux simple_loader.c
-fPIC表示position-independent code

参考文档

Type Signatures
jni functions.html

Posted in: java基础

Comments are closed.