dev c++ dll 製作與呼叫學習筆記
一、製作 dll檔案
通過建立 dll 工程 如 DLLTEST 右擊工程 new File ,記得#include"dll.h"
1、 再寫函式 如
int show_string(char * str){
.........
}
2、 在dll.h 中加上 DLLIMPORT show_string(char * str);
編譯得到兩個有用的東西。
DLLTEST.DLL
libDLLTEST.a
二、dll 載入與呼叫
載入分靜態 與 動態
靜態很簡單,add Library of Object 先擇.a檔案
動態載入可以不用.a 檔案 只要有 .dll 檔案就夠
示例:
#include <stdlib.h>
#include<stdio.h>
#include<wtypes.h>
#include<windows.h>
int main(int argc, char *argv[])
{
typedef int (*FUNT)(char * str);// 函式指標型別
HINSTANCE Hint = LoadLibrary("C:/Users/LiuBin/Desktop/Finger/DLLTEST.DLL");// 載入 dll
FUNT show_string = (FUNT)GetProcAddress(Hint,"show_string");// 取得 dll 匯出的 show_string方法
printf("%d",show_string);
if(!show_string){
MessageBox(0,"load dll error","ERROR",MB_ICONINFORMATION);
}else{
show_string("my string");
}
system("PAUSE");
return 0;
}
製作好dll 後同樣可以用其它語言去呼叫如:java 通過 jNative 呼叫。
以下是呼叫示例
package cn.connectDll;
import org.xvolks.jnative.JNative;
import org.xvolks.jnative.Type;
public class ConnectDll {
public static void main(String args[]){
testFromPath("E:/dev C++ work");
}
public static int testFromPath(String path){
path+="/DllTest.dll";
//通過絕對路徑加裝檔案
System.load(path);
show_string();
System.out.println("裝載完成");
return 0;
}
public static int show_string(){
JNative n=null;
try{
n=new JNative("DllTEST.dll","show_string");
n.setRetVal(Type.INT);
int i=0;
n.setParameter(i++, "show_string");
n.invoke();
String str= n.getRetVal();
System.out.println("返回值"+str);
return 0;
}catch(Exception ef){
ef.printStackTrace();
}
return 1;
}
}