java jni c++ 例子,javajni例子

來源:互聯網
上載者:User

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。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.