1. 程式人生 > >java 呼叫c++ dll

java 呼叫c++ dll

java
程式碼

package umessage;


public class TestJNI {
	
	public String name = "";
	
	TestJNI(){
		
    }
	
	static {
		System.loadLibrary("TestJNI");
	}

	public native String PrintFF(StringOut args);
	public native void PrintGG();
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		TestJNI str = new TestJNI();
		StringOut strOut = new StringOut();
				
		String st = str.PrintFF(strOut);
		
		System.out.println(st);
		System.out.println(strOut.args);
		
		
		str.PrintGG();
		
		System.out.println(str.name);

	}

}


c++
程式碼

/* DO NOT EDIT THIS FILE - it is machine generated */
#include "jni.h"
/* Header for class umessage_TestJNI */

#ifndef _Included_umessage_TestJNI
#define _Included_umessage_TestJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     umessage_TestJNI
 * Method:    PrintFF
 * Signature: (Lumessage/StringOut;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_umessage_TestJNI_PrintFF
  (JNIEnv *, jobject, jobject);

/*
 * Class:     umessage_TestJNI
 * Method:    PrintGG
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_umessage_TestJNI_PrintGG
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif



c++

#include "umessage_TestJNI.h"
#include <iostream>

using namespace std;



// // 	const char* str;
// // 	str = env->GetStringUTFChars(jstr, false);
// // 
// // 	if (str == NULL) {
// // 		return 0;/* OutOfMemoryError already thrown */
// // 	}
// // 
// // 	std::cout << str << std::endl;
// // 
// // 	env->ReleaseStringUTFChars(jstr, str);
// 
// 
// 
// 
// 
// 	const char * pstr = "hello word";
// 	jstring jstrt = env->NewStringUTF(pstr);
// 
// 	return jstrt;
// }

	JNIEXPORT void JNICALL Java_umessage_TestJNI_PrintGG
	(JNIEnv * env, jobject obj)
	{
		const char * name = "hello word";
		jstring jstrName = env->NewStringUTF(name);
		jclass cls = env->FindClass("umessage/TestJNI");
		//jclass cls = env->GetObjectClass(obj);
		jfieldID fid = env->GetFieldID(cls, "name", "Ljava/lang/String;");
		env->SetObjectField(obj, fid, jstrName);
	}


	JNIEXPORT jstring JNICALL Java_umessage_TestJNI_PrintFF
	(JNIEnv *env, jobject obj, jobject arg)
	{
		jclass stringOutcl = env->FindClass("umessage/StringOut");
		jmethodID InitId = env->GetMethodID(stringOutcl, "<init>", "(Ljava/lang/String;)V");

		jstring native_str = env->NewStringUTF("aaaaaaaaaaaaaaaaaaaaaaaaa");
		env->CallVoidMethod(arg, InitId, native_str);

		const char *pstr = "hello word hello word";
		jstring  jstr = env->NewStringUTF(pstr);
		return jstr;
	}