1. java程式 2 編譯 javac TestHello.java 3. 生成c++頭文件 javah TestHello 4. 創建 DLL動態鏈接庫工程 TestHello visual studio 2010: File->new->project->win32 project-> dll ...
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 once class 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。