泥瓦匠初次遇見 navicat 是在 java.lang.object 源碼中的一個hashcode方法:
1
<code>public native int hashcode();</code>
為什麼有個navicat呢?這是我所要學習的地方。是以今天泥瓦匠想要總結下navicat。
凡是一種語言,都希望是純。比如解決某一個方案都喜歡就單單這個語言來寫即可。java平台有個使用者和本地c代碼進行互操作的api,稱為java native interface (java本地接口)。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLi1WdoR3XldWYtl2LcRDMvwVNxAjMvw1ckF2bsBXdvwFduVGdu92YtA3dvwVbvNmL0V2aj92c5JmL3d3dvw1LcpDc0RHaiojIsJye.png)
我們需要按照下班友善的步驟進行:
1、建立一個java類,裡面包含着一個 native 的方法和加載庫的方法 loadlibrary。hellonative.java 代碼如下:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<code>public class hellonative</code>
<code>{</code>
<code> </code><code>static</code>
<code> </code><code>{</code>
<code> </code><code>system.loadlibrary("hellonative");</code>
<code> </code><code>}</code>
<code> </code>
<code> </code><code>public static native void sayhello();</code>
<code> </code><code>@suppresswarnings("static-access")</code>
<code> </code><code>public static void main(string[] args)</code>
<code> </code><code>new hellonative().sayhello();</code>
<code>}</code>
首先泥瓦匠讓大家注意的是native方法,那個加載庫的到後面也起作用。native
關鍵字告訴編譯器(其實是jvm)調用的是該方法在外部定義,這裡指的是c。如果大家直接運作這個代碼, jvm會告之:“a java
exception has occurred.”控制台輸出如下:
<code>exception in thread "main" java.lang.unsatisfiedlinkerror: no hellonative in java.library.path</code>
<code> </code><code>at java.lang.classloader.loadlibrary(unknown source)</code>
<code> </code><code>at java.lang.runtime.loadlibrary0(unknown source)</code>
<code> </code><code>at java.lang.system.loadlibrary(unknown source)</code>
<code> </code><code>at hellonative.<</code><code>clinit</code><code>>(hellonative.java:5)</code>
這是程式使用它的時候,虛拟機說不知道如何找到sayhello。下面既可以手動寫,自然泥瓦匠是用
2、運作javah,得到包含該方法的c聲明頭檔案.h
泥瓦匠将hellonative.java ,簡單地 javac javah,如圖
就得到了下面的 hellonative.h檔案 :
16
17
18
19
20
21
<code>/* do not edit this file - it is machine generated */</code>
<code>#include <</code><code>jni.h</code><code>></code>
<code>/* header for class hellonative */</code>
<code>#ifndef _included_hellonative</code>
<code>#define _included_hellonative</code>
<code>#ifdef __cplusplus</code>
<code>extern "c" {</code>
<code>#endif</code>
<code>/*</code>
<code> </code><code>* class: hellonative</code>
<code> </code><code>* method: sayhello</code>
<code> </code><code>* signature: ()v</code>
<code> </code><code>*/</code>
<code>jniexport void jnicall java_hellonative_sayhello</code>
<code> </code><code>(jnienv *, jclass);</code>
jni.h 這個檔案,在/%java_home%include
3、根據頭檔案,寫c實作本地方法。
這裡我們簡單地實作這個sayhello方法如下:
<code>#include "hellonative.h"</code>
<code>#include <</code><code>stdio.h</code><code>></code>
<code> </code><code>printf("hello,jni"); </code>
4、生成dll共享庫,然後java程式load庫,調用即可。
在windows上,mingw gcc 運作如下
<code>gcc -m64 -wl,--add-stdcall-alias -i"c:\program files\java\jdk1.7.0_71\include" -i"c:\program files\java\jdk1.7.0_71\include\include\win32" -shared -o hellonative.dll hellonative.c</code>
-m64表示生成dll庫是64位的。然後運作 hellonative:
<code>java hellonative</code>
終于成功地可以看到控制台列印如下:
<code>hello,jni</code>