LINUX 下的 java 与 C++ 互相调用
Hello.java
public class Hello
{
static
{
try
{
// 此处即为本地方法所在链接库名
System.loadLibrary("hello");
}
catch(UnsatisfiedLinkError e)
{
System.err.println( "Cannot load hello library:n " +
e.toString() );
}
}
public Hello()
{
}
// 声明的本地方法
public native void SayHello(String strName);
public static void main(String[] args){
System.out.println("1111111");
}
public void print(){
System.out.println("native call java");
}
}
javac Hello.java ; javah Hello.java
产生Hello.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class Hello */
#ifndef _Included_Hello
#define _Included_Hello
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Hello
* Method: SayHello
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_Hello_SayHello
(JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif
编写Hello.cpp
#include "Hello.h"
#include
// 与 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,%sn",str);
//调用java代码
try{
jclass cls = env->GetObjectClass(arg);
jmethodID print= env->GetMethodID(cls,"print","()V");
env->CallIntMethod(arg,print);
}catch(int){
printf("ERRRR");
}
return;
}
编译
#!/bin/bash
export LD_LIBRARY_PATH='~/c/jni/':$LD_LIBRARY_PATH
echo "g++ -I/home/huaonline/libs/jdk/include -I/home/huaonline/libs/jdk/include/linux -fPIC -c Hello.cpp"
g++ -I/home/huaonline/libs/jdk/include -I/home/huaonline/libs/jdk/include/linux -fPIC -c Hello.cpp
echo "g++ -shared -Wl,-soname,libhello.so.1 -o libhello.so.1.0 Hello.o"
g++ -shared -Wl,-soname,libhello.so.1 -o libhello.so.1.0 Hello.o
echo "cp libhello.so.1.0 libhello.so"
cp libhello.so.1.0 libhello.so
java ToSay
结果
g++ -I/home/huaonline/libs/jdk/include -I/home/huaonline/libs/jdk/include/linux -fPIC -c Hello.cpp
g++ -shared -Wl,-soname,libhello.so.1 -o libhello.so.1.0 Hello.o
cp libhello.so.1.0 libhello.so
Hello,John
native call java
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.e1idc.net