java jni c++ 例子,javajni例子
1. java程式
public class TestHello { static { System.loadLibrary("TestHello"); } public static native int add(int a, int b); public static void main(String[] args) { int c = add(2, 5); System.out.print("result:::::"+c); }}
2 編譯
javac TestHello.java
3. 產生c++標頭檔
javah TestHello
4. 建立 DLL動態連結程式庫工程 TestHello
visual studio 2010: File->new->project->win32 project-> dll->TestHello
5. 引入 jni.h, jni_md.h TestHello.h
TestHello工程右鍵-> Properties->Configuration Properties->C/C++ ->General -> Additional Include Directories
6. 在TestHello.cpp中 實現TestHello.h中的函數
// TestHello.cpp : Defines the exported functions for the DLL application.//#include "stdafx.h"#include "dllApi.h"JNIEXPORT jint JNICALL Java_TestHello_add (JNIEnv * env, jclass obj, jint a, jint b){ int var =0; dllApi* test = new dllApi(); var = test->DLL_API_ADD(a, b); delete test; return var;};
dllApi.h
#pragma onceclass dllApi{public: dllApi(void); ~dllApi(void); int DLL_API_ADD(int , int ); int DLL_API_SUB(int , int ); int DLL_API_MUL(int , int ); int DLL_API_DIV(int , int ); };
dllApi.cpp
#include "StdAfx.h"#include "dllApi.h"dllApi::dllApi(void){}dllApi::~dllApi(void){}int dllApi :: DLL_API_ADD(int a, int b){ return (a + b);};int dllApi :: DLL_API_SUB(int a, int b){ return (a-b);};int dllApi :: DLL_API_MUL(int a, int b){ return (a*b);};int dllApi :: DLL_API_DIV(int a, int b){ return (a/b);};
7. 編譯產生TestHello.dll
8. 將dll檔案拷貝到class目錄下, 執行class檔案,OK。