在工程項目中,為了不暴露源代碼和避免嚴重耦合,所以將代碼封裝成 .dll二進制文件,以供項目調用。
這幾天,也是在看這些封裝dll,并使用Java中的JNA調用c++的dll鏈接庫中的函數,做個筆記!
1、創建dll
新建項目 -> Win32項目 -> 應用程序類型:DLL ?附加選項:預編譯頭、安全開發生命周期檢查
2、編寫程序
在頭文件中添加 mydll.h
#pragma once
#define MYLIBAPI ?extern ? "C" ? ? __declspec( dllexport ) ?
?
MYLIBAPI void say(wchar_t* pValue);
?
struct UserStruct {
?? ?long id;
?? ?wchar_t* ?name;
?? ?int age;
};
?
MYLIBAPI void sayUser(UserStruct* pUserStruct);
?
struct CompanyStruct {
?? ?long id;
?? ?wchar_t* ?name;
?? ?// ?UserStruct* ?users[100]; ?
?? ?UserStruct ? users[100];
?? ?int count;
};
?
struct CompanyStruct2 {
?? ?long id;
?? ?wchar_t* ?name;
?? ?UserStruct* ?users[100];
?? ?// UserStruct ? users[100]; ?
?? ?int count;
};
?
MYLIBAPI void sayCompany(CompanyStruct* pCompanyStruct);
?
MYLIBAPI void sayCompany2(CompanyStruct2* pCompanyStruct);
其中的 #define MYLIBAPI ?extern ? "C" ? ? __declspec( dllexport ) ? 一定不要忘,這句的意思是導出dll
在mydll.cpp文件中:
#include <iostream> ?
#include "Out.h" ?
?
void ?say(wchar_t* pValue) {
?? ?std::wcout.imbue(std::locale("chs"));
?? ?std::wcout << L"上帝說:" << pValue << std::endl;
}
?
void sayUser(UserStruct* pUserStruct) {
?? ?std::wcout.imbue(std::locale("chs"));
?? ?std::wcout << L"ID:" << pUserStruct->id << std::endl;
?? ?std::wcout << L"姓名:" << pUserStruct->name << std::endl;
?? ?std::wcout << L"年齡:" << pUserStruct->age << std::endl;
}
?
void sayCompany(CompanyStruct* pCompanyStruct) {
?? ?std::wcout.imbue(std::locale("chs"));
?? ?std::wcout << L"ID:" << pCompanyStruct->id << std::endl;
?? ?std::wcout << L"公司名稱:" << pCompanyStruct->name << std::endl;
?? ?std::wcout << L"員工總數:" << pCompanyStruct->count << std::endl;
?? ?for (int i = 0; i<pCompanyStruct->count; i++) {
?? ??? ?sayUser(&pCompanyStruct->users[i]);
?? ?}
}
?
void sayCompany2(CompanyStruct2* pCompanyStruct) {
?? ?std::wcout.imbue(std::locale("chs"));
?? ?std::wcout << L"ID:" << pCompanyStruct->id << std::endl;
?? ?std::wcout << L"公司名稱:" << pCompanyStruct->name << std::endl;
?? ?std::wcout << L"員工總數:" << pCompanyStruct->count << std::endl;
?? ?for (int i = 0; i<pCompanyStruct->count; i++) {
?? ??? ?sayUser(pCompanyStruct->users[i]);
?? ?}
}
?添加頭文件就可以了,如果需要opencv或者pcl這樣的函數庫,在電腦上配置一下環境就可以了
3、生成解決方案
注意:如果jar的是64的,則需要生成64版本的,32位的同理,不然在使用Java調用dll文件時候,會一直找不到dll文件,很煩!!
在x64的Debug目錄下生成了mydll.dll和mydll.lib文件。將dll lib h三個文件拷貝出來備用
4、c++調用封裝好的dll
隱式調用,我覺得隱式調用還是比較方便的
正常的新建項目,像配置opencv環境那樣,在屬性管理器中,更改屬性表:
Vc++目錄下 包含目錄 中添加.h文件路徑
? ? ? ? ? ? ? ? ? ? 庫目錄 中添加.lib文件路徑
鏈接器 輸入 附加依賴項 添加 xx.lib
將.dll文件放到Demo工程目錄下(右擊項目名--在文件資源管理器中打開文件夾)或者System32文件夾中。