要調用C語言函數,可以使用Java Native Interface(JNI)來實現。以下是一個簡單的示例:
#include <stdio.h>
void sayHello() {
printf("Hello from C!\n");
}
public class NativeLibrary {
static {
System.loadLibrary("libraryname"); //加載共享庫文件,libraryname是共享庫文件的名稱
}
public native void sayHello(); //聲明native方法
public static void main(String[] args) {
NativeLibrary library = new NativeLibrary();
library.sayHello(); //調用C語言函數
}
}
javac NativeLibrary.java
javah NativeLibrary
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class NativeLibrary */
#ifndef _Included_NativeLibrary
#define _Included_NativeLibrary
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: NativeLibrary
* Method: sayHello
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_NativeLibrary_sayHello
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
#include "NativeLibrary.h"
#include <stdio.h>
JNIEXPORT void JNICALL Java_NativeLibrary_sayHello(JNIEnv *env, jobject obj) {
printf("Hello from C!\n");
}
java NativeLibrary
通過以上步驟,就可以在Java中調用C語言函數了。需要注意的是,JNI調用C語言函數需要仔細處理數據類型和內存管理,以避免內存泄漏和程序崩潰。