定义一个native 方法:
package ext;
import java.util.Hashtable;
public class TestJNI
{
static
{
System.loadLibrary("dllfile");
}
public TestJNI()
{
Hashtable htable = new Hashtable();
htable.put(1,2);
}
public native Hashtable getNameList();
public static void main(String[] arg)
{
TestJNI tstJNI= new TestJNI();
Hashtable htable= tstJNI.getNameList();
System.out.println(htable.size());
}
}
通过 javah 生成 头文件 ext_TestJNI.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include "jni.h"
/* Header for class ext_TestJNI */
#ifndef _Included_ext_TestJNI
#define _Included_ext_TestJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: ext_TestJNI
* Method: getNameList
* Signature: ()Ljava/util/Hashtable;
*/
JNIEXPORT jobject JNICALL Java_ext_TestJNI_getNameList
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
在c++创建一个dynamic dll项目,并在 StdAfx.h 中 include 头文件 ext_TestJNI.h
StdAfx.h 代码:
#if !defined(AFX_STDAFX_H__FAD3F2E4_D6E1_4011_9791_2256C4B0BDE6__INCLUDED_)
#define AFX_STDAFX_H__FAD3F2E4_D6E1_4011_9791_2256C4B0BDE6__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// Insert your headers here
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include "ext_TestJNI.h"
在 CPP文件中定义 方法实现:
CPP代码:
#include "stdAfx.h"
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
JNIEXPORT jobject JNICALL Java_ext_TestJNI_getNameList
(JNIEnv *env, jobject jobj)
{
jclass class_Hashtable=env->FindClass("java/util/Hashtable");
jmethodID construct_method=env->GetMethodID( class_Hashtable, "<init>","()V");
jobject obj_Map =env->NewObject( class_Hashtable, construct_method, "");
jmethodID add_method= env->GetMethodID(class_Hashtable,"put","(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
env->CallObjectMethod(obj_Map,add_method,env->NewStringUTF((char*)"1"),env->NewStringUTF((char*)"person1"));
env->CallObjectMethod(obj_Map,add_method,env->NewStringUTF((char*)"2"),env->NewStringUTF((char*)"person2"));
return obj_Map;
}
注:
javap -s <类名> 查看 类方法的 signature