要调用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语言函数需要仔细处理数据类型和内存管理,以避免内存泄漏和程序崩溃。