JNI(一):初识JNI

您所在的位置:网站首页 nativetest环境 JNI(一):初识JNI

JNI(一):初识JNI

#JNI(一):初识JNI| 来源: 网络整理| 查看: 265

       通过JNI实现一个Hello world。

       1. 在Java类中声明native方法,NativeTest.java。

package com.ghsau; public class NativeTest { public native void sayHello();// native修饰的方法不能有方法体 public static void main(String[] args) { System.loadLibrary("native");// 加载DLL NativeTest nt = new NativeTest(); nt.sayHello(); } }

       2. 用javah将编译后的class文件生成头文件,我用的是eclipse,自动编译的class文件在bin目录下,在dos环境下进入到bin目录,执行javah com.ghsau.NativeTest,这样就在class文件所在目录下生成了com_ghsau_NativeTest.h头文件。

       3. 用vc++新建一个Win32 Dynamic Link Library工程(我的是vc++6.0),输入工程名(我的是native),然后选择create a simple dll project,创建成功之后,在source files下有native.cpp(和工程名一样)和StdAfx.cpp,在Header Files下有StdAfx.h,首先先编译一下StdAfx.cpp,会在工程所在目录debug文件夹下生成native.pch文件,这个文件在编译native.cpp的时候需要用到;然后在Header Files中引入com_ghsau_NativeTest.h、jni.h(com_ghsau_NativeTest.h需要,在jdk安装目录include下)、jni_md.h(jni.h需要,在include/win32下);最后编辑com_ghsau_NativeTest.h、native.cpp,编辑后代码如下:

       com_ghsau_NativeTest.h

/* 将修改为"jni.h" */ #include "jni.h" /* Header for class com_ghsau_NativeTest */ #ifndef _Included_com_ghsau_NativeTest #define _Included_com_ghsau_NativeTest #ifdef __cplusplus extern "C" { #endif /* * Class: com_ghsau_NativeTest * Method: sayHello * Signature: ()V * 生成dll需要在方法前加上extern "C" __declspec(dllexport) */ extern "C" __declspec(dllexport) JNIEXPORT void JNICALL Java_com_ghsau_NativeTest_sayHello (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif

       native.cpp

#include "stdafx.h" #include "com_ghsau_NativeTest.h" #include BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; } JNIEXPORT void JNICALL Java_com_ghsau_NativeTest_sayHello(JNIEnv * env, jobject obj) { cout


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3