谁能给我写一个linux下的java调用C代码的例子?我执行老是出问题
1个回答
展开全部
java
public class HelloWorld
{
static
{
System.loadLibrary("native");
//对应C语言 动态库的名字
}
private native int hello(int[]arr,int num);
public static void main (String [] args)
{
int[]arr = {1,2,3,4};
HelloWorld n = new HelloWorld();
System.out.println(n.hello(arr,arr.length));
}
}
头文件
#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: HelloWorld
* Method: hello
* Signature: ([I)I
*/
JNIEXPORT jint JNICALL Java_HelloWorld_hello
(JNIEnv *, jobject, jintArray);
#ifdef __cplusplus
}
#endif
#endif
c
#include <jni.h>
jint jhello(JNIEnv *env,jobject obj,jintArray arr,jint num)
{
jint *carr;
jint i, sum = 0;
carr = (*env)->GetIntArrayElements(env, arr, NULL);
if (carr == NULL) {
return 0; /* exception occurred */
}
for (i=0; i<num; i++) {
sum += carr[i];
}
(*env)->ReleaseIntArrayElements(env, arr, carr, 0);
return sum;
}
JNINativeMethod method[] =
{
"hello","([II)I",(void *)jhello,
};
jint JNI_OnLoad(JavaVM *jvm,void *reserved)
{
printf("jnionload \n");
JNIEnv *env;
jclass jcls;
if((*jvm) ->GetEnv(jvm,(void **)&env,JNI_VERSION_1_2))
{
return JNI_ERR;
}
jcls = (*env) -> FindClass(env,"HelloWorld");
if(jcls == NULL)
{
return JNI_ERR;
}
(*env) -> RegisterNatives(env,jcls,method,sizeof(method)/sizeof(JNINativeMethod));
return JNI_VERSION_1_2;
}
主要是用jni.
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询