JAVA調用動態鏈接庫(dll)


   


菜雞爬坑 基礎知識  
因為某個東西的keygen我只會在win下生成!! 所以只能出此下策!!
之前一直是android下用jni調用so文件,現在試下java在win平台下調用dll 首先還是老套路,直接在dll中彈出一個信息框具體流程如下:在Java中定義一個方法,在C++中實現這個方法,在方法內彈出信息框.
首先在java中定義一個類 
代碼:
package cn.ylca.dll;
public class DllEntity {
//本地方法
         public native void messagebox();
}

第二步 控制台到bin目錄下
使用javah生成DllEntity 的頭文件


生成文件內容如下
代碼:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class cn_ylca_dll_DllEntity */

#ifndef _Included_cn_ylca_dll_DllEntity
#define _Included_cn_ylca_dll_DllEntity
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class:     cn_ylca_dll_DllEntity
* Method:    messagebox
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_cn_ylca_dll_DllEntity_messagebox
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif
第三步新建一個dll的項目

然后把剛才生成的內容復制到cpp文件   到這里還需要一個jni.h頭文件  到jdk目錄下 include 文件中復制一份 
代碼如下
代碼:
// javadll.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
BOOL APIENTRY DllMain( HANDLE hModule, 
                       DWORD  ul_reason_for_call, 
                       LPVOID lpReserved
                                         )
{
    return TRUE;
}
/* DO NOT EDIT THIS FILE - it is machine generated */
#include "jni.h"
/* Header for class cn_ylca_dll_DllEntity */

#ifndef _Included_cn_ylca_dll_DllEntity
#define _Included_cn_ylca_dll_DllEntity
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class:     cn_ylca_dll_DllEntity
* Method:    messagebox
* Signature: ()V
*/
        
JNIEXPORT void JNICALL Java_cn_ylca_dll_DllEntity_messagebox
(JNIEnv *env, jobject obj){//補上參數名字

        //到這里就不許要再說什么的了把! 
        MessageBox(NULL, "測試!", "demo", 0);
}

#ifdef __cplusplus
}
#endif
#endif
第四步就是如何在java中使用了  創建一個測試類來調用




代碼:
public class Test {
        public static void main(String[] args) {
                //加載指定路徑的dll
                System.load("D://javadll//Debug//javadll.dll");
                //創建本地方法對象
                DllEntity dllEntity = new DllEntity();
                //調用方法
                dllEntity.messagebox();
        }
   

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM