这两天在弄一个通过JNI在java里和C程序中传参和取返回值的程序,相关资料较少,调试费劲,真是头大了,还好终于搞定了:
Hello.java
public class Hello
{
static
{
try
{
//此处即为本地方法所在链接库名
System.load("//usr/lib/libhello.so");
}
catch(UnsatisfiedLinkError e)
{
System.err.println( "Cannot load hello library:\n " +
e.toString() );
}
}
public Hello()
{
}
//声明的本地方法
public native void SayHello(String strName);
}
=======================================================
ToSay.java
public class ToSay {
public static void main(String args[]){
Hello hw = new Hello();
hw.SayHello("Christmas");
}
}
=======================================================
Hello.c
#include "Hello.h"
#include <stdio.h>
//与Hello.h中函数声明相同
JNIEXPORT void JNICALL Java_Hello_SayHello (JNIEnv * env, jobject arg, jstring instring)
{
//从instring字符串取得指向字符串UTF编码的指针
const jbyte *str = (const jbyte *)env->GetStringUTFChars( instring, JNI_FALSE );
printf("Hello,%s\n",str);
//通知虚拟机本地代码不再需要通过str访问Java字符串。
env->ReleaseStringUTFChars( instring, (const char *)str);
return;
}
=======================================================
gcc -I/usr/java/include -shared -o libhello.so Hello.c
报错:
Hello.c: In function `Java_Hello_SayHello':
Hello.c:7: request for member `GetStringUTFChars' in something not a structure or union
Hello.c:10: request for member `ReleaseStringUTFChars' in something not a structure or union
=======================================================
将Hello.c改名为Hello.cpp后执行gcc -I/usr/java/include -shared -o libhello.so Hello.cpp后成功编译
=======================================================
执行java ToSay后报错:
Cannot load hello library:
java.lang.UnsatisfiedLinkError: /usr/lib/libhello.so: /usr/lib/libhello.so: undefined symbol: __gxx_personality_v0
Exception in thread "main" java.lang.UnsatisfiedLinkError: SayHello
at Hello.SayHello(Native Method)
at ToSay.main(ToSay.java:4)
=======================================================
改为:g++ -I/usr/java/include -shared -o libhello.so Hello.cpp编译后执行java ToSay程序成功。
=======================================================
改为:g++ -I/usr/java/include -shared -o libhello.so Hello.c编译后执行java ToSay程序也成功。