2012-04-03 50 views
1

我使用JNI通过将许多变量从Java到CJNI多个变量

public native int[] intArrayMethod(int[] t,int nbr,int tag); 

我如何可以在C使用这些变量? 我已经生成的头文件,我得到:

#ifndef _Included_MainClass 
#define _Included_MainClass 

#ifdef __cplusplus 
extern "C" 
{ 
#endif 

/* 
Class:  MainClass 
Method: intArrayMethod 
Signature: ([FII)[I 
*/ 

    JNIEXPORT jintArray JNICALL Java_MainClass_intArrayMethod 
     (JNIEnv *, jobject, jfloatArray, jint, jint); 

#ifdef __cplusplus 
} 
#endif 

#endif 

如何使用我的C代码传递的变量?

+1

[你尝试过什么?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – 2012-04-03 11:39:14

+0

您的Java方法和JNI方法签名不匹配。 (int []和jfloatArray)。使用javah生成签名。它可以节省很多痛苦。 – jogabonito 2012-04-03 12:03:53

回答

0
  • 写一个.c文件以匹配 - 相同的头文件,但带有body和参数名称。
  • 做一些与变量
  • 返回结果

代码:

#include "foo.h" 
JNIEXPORT jintArray JNICALL Java_MainClass_intArrayMethod 
(JNIEnv * env, jobject obj, jfloatArray arr, jint a, jint b) { 

    jintArray ret[2]; 
    ret[0] = a + b; 
    ret[1] = arr[0] + arr[1]; 
    return ret; 
} 

像这样的东西编译:

gcc -shared foo.c -I/path/to/java/include -o libfoo.so 

不要忘了包括在您的Java代码中载入行:

static { 
    System.loadLibrary("foo"); // does not include lib prefix, or .dll/.so suffix! 
} 

用此运行,(假设在当前目录中为libfoo.so)。

java -Djava.library.path=. Foo