Created
May 11, 2013 14:27
-
-
Save masazdream/5560107 to your computer and use it in GitHub Desktop.
JNI_javaからcppを実行する<0>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
JNI Javaからcppを呼び出してみる。 | |
■まずはJavaでコード書きます | |
https://gist.github.com/masazdream/5560075 | |
<script src="https://gist.github.com/masazdream/5560075.js"></script> | |
■対応するCppファイルを書きます | |
https://gist.github.com/masazdream/5560082 | |
<script src="https://gist.github.com/masazdream/5560082.js"></script> | |
※Javaのコードとの名称対応は大切です。 | |
■JavaとCppのコードから必要なヘッダファイルとSharedObjectを作成します | |
そのために今回はantを使用しますので、antからgccコンパイルする環境を作成します。 | |
・ant-contribのバイナリをantのlibに配置 | |
http://sourceforge.net/projects/ant-contrib/files/ | |
・ant-xercesのバイナリを取得して、antoのlibに配置 | |
http://xerces.apache.org/mirrors.cgi | |
・ant-cpptasksを作成する。 | |
http://sourceforge.net/projects/ant-contrib/files/ant-contrib/cpptasks-1.0-beta5/ | |
デフォルトでついてくるbuild.xmlに以下の対策を施して、実行するとjarが作成出来ます。 | |
■対策 | |
①javacタグにincludeAntRuntime="true"を設定します。 | |
②ソースをコンパイルするJavaのバージョンに注意しないと警告が | |
うるさいので処理します。 | |
A. java.sourceとjavac.targetには、コンパイルするJavaのバージョンを | |
設定しましょう。 | |
B. jt.jarのパスを表すpathを作成して、javacのbootclasspathに指定します。 | |
<path id="compile.boot.path"> | |
<fileset dir="${java.home}/lib"> | |
<include name="rt.jar" /> | |
</fileset> | |
</path> | |
<javac ・・・ | |
<bootclasspath refid="compile.boot.path" /> | |
</javac> | |
■必要なパスを通す | |
③xercesのライブラリを暮らすパスに追加する | |
<path id="compile.path"> | |
<fileset dir="[最初のステップでjarを置いたディレクトリ]"> | |
<include name="*.jar" /> | |
</fileset> | |
</path> | |
<javac ・・・ | |
<classpath refid="compile.path" /> | |
</javac> | |
これでコンパイル出来ます。 | |
target/lib/cpptasks.jarがあるので、ant本体のlibディレクトリに | |
コピーします。 | |
> echo $ANT_HOME | |
でhomeを確認が出来たら、配下のlibにコピーします。 | |
■antの記述を整えます。 | |
javahでヘッダーファイル作成を記述します。 | |
ccタスクでcppファイルをコンパイルします。 | |
<taskdef resource="cpptasks.tasks">でccタスクを使用する準備が出来ますので、 | |
以下のようにccタスクを記述します。 | |
<cc link="shared" outfile="[soを出力するディレクトリ名]/[クラス名]" obj="[ヘッダーファイルを出力したディレクトリ]"> | |
<includepath location="${env.JAVA_HOME}/include}" /> | |
<includepath location="${env.JAVA_HOME}/include/linux" /> | |
<fileset dir="[ヘッダーファイルを出力したディレクトリ]" includes="HelloWorldJNI.cpp" /> | |
<libset libs="stdc++"> ←cppの場合は指定。CとCPPが混じっている場合には、cppファイルのみにantで実行出来ます。 | |
</cc> | |
※outputfileに指定したパスのファイル名をつかって、libhello.soなどの名前が決定されます。 | |
最終的に以下の様なファイルになる。https://gist.github.com/masazdream/5560085 | |
<script src="https://gist.github.com/masazdream/5560085.js"></script> | |
■Javaの実行 | |
soファイルの入ったディレクトリを環境変数「LD_LIBRARY_PATH」に指定してから実行します。 | |
実行結果は、Hello World。 | |
cppで書いたコードがJavaで実行出来ます。 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment