Eclipse+MinGW+SWIG封裝Java介面

來源:互聯網
上載者:User
A.  建立並實現C++類庫

設計這個類庫的名字為SwigLib,其中需要一個Random類來產生隨機數。首先在Eclipse中建立Shared Library Project:

添加Random類:

/*

 * Random.h

 */

 

#ifndef RANDOM_H_

#define RANDOM_H_

 

namespace SwigLib {

 

class
Random {

public:

    Random();

    int getInt(int max);

    virtual ~Random();

};

 

} /* namespaceSwigTest */

#endif /* RANDOM_H_ */

 

/*

 *Random.cpp

 */

 

#include
"Random.h"

#include
<stdlib.h>

#include
<ctime>

 

namespace SwigLib {

 

Random::Random() {

    srand((unsigned)time(0));

}

 

int Random::getInt(int max) {

    return
rand
() % max;

}

 

Random::~Random() {

}

 

} /* namespaceSwigLib */

 

B.  使用SWIG產生Java代碼

從http://www.swig.org/download.html下載swigwin-x.x.x,解壓縮。

編寫SWIG能識別的介面檔案,這個檔案將被SWIG讀取並產生相應的不同語言的介面代碼,在這裡建立介面檔案SwigLib.i:

%module SwigLib

%{

#include "Random.h"

%}

 

%include "Random.h"

調用SWIG命令列產生Java代碼和相應的C++封裝代碼:

D:\Software\Develop\SWIG\swigwin-2.0.6>swig -c++ -java -packagenet.wuyf D:\wuyf\Workspace\C\SwigLib\src\SwigLib.i

 

C.  編譯產生動態連結程式庫

由於產生的Java代碼中需要引用JNI,因此編譯前必須把Java的一些include目錄添加到Eclipse中去:

右鍵工程->Properties->C/C++General->Paths and Symbols,把%JAVA_HOME%/include和%JAVA_HOME%/include/win32路徑添加到編譯環境的Includes中:

在Windows的Eclipse中編譯Java可以調用的連結庫還需要一個非常重要的參數配置,右鍵工程->Properties->C/C++Build->Settings,在Tool Settings中的MinGW C++ Linker中修改Command,添加-Wl,--add-stdcall-alias選項(參考http://www.swig.org/tutorial.html):

下面,使用Eclipse編譯!

 

D. 在Java中調用連結庫

首先注意,在Windows上用MinGW產生的是32位的連結庫,因此需要32位的JDK進行調用。下面將SWIG產生的Java類複製到Java工程中,注意包名保持一致,測試調用:

package net.wuyf;

 

importorg.testng.Assert;

importorg.testng.annotations.BeforeClass;

importorg.testng.annotations.Test;

 

public classRandomTest {

    privateRandom r = null;

    privatestatic int maxInt = 100;

   

    static{

        System.load("D:\\wuyf\\Workspace\\C\\SwigLib\\Debug\\libSwigLib.dll");

      }

 

    @BeforeClass

    publicvoid beforeClass() {

        r = newRandom();

    }

 

    @Test(threadPoolSize= 1, invocationCount = 100)

    publicvoid getInt() {

        inti = r.getInt(maxInt);

        Assert.assertTrue(i>= 0 && i < maxInt);

        System.out.println(i);

    }

}

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.