首先在一個解決方案中創建了三個項目,如下圖所示:

DLL_TEST項目的配置類型是exe。另外兩個項目的配置類型是dll

三個項目的文件路徑排列如下所示:

x64文件夾中是三個項目編譯生成的文件所在地。
三個項目中的文件:

Shared_lib.h文件代碼如下:
#pragma once
#include <cstdio>
#include <cstdlib>
#include <windows.h>
class Shared_lib
{
public:
Shared_lib(const char* lib_name);
~Shared_lib();
void* getFunc(const char* func_name);
private:
const char* m_lib_name;
HMODULE m_handle;
};
Shared_lib.cpp文件代碼如下
#include "Shared_lib.h"
Shared_lib::Shared_lib(const char* lib_name) :
m_lib_name(_strdup(lib_name))
{
if (m_lib_name == nullptr)
{
m_handle = nullptr;
}
else
{
m_handle = LoadLibrary(m_lib_name);
}
}
Shared_lib::~Shared_lib()
{
if (m_handle != nullptr)
{
FreeLibrary(m_handle);
}
if (m_lib_name != nullptr)
{
delete m_lib_name;
m_lib_name = nullptr;
}
}
void* Shared_lib::getFunc(const char* func_name)
{
if (m_handle != nullptr)
{
void* func = GetProcAddress(m_handle, func_name);
return func;
}
return nullptr;
}
調用LoadLibrary函數需要將項目的字符集改成多字節字符集,不然參數無法使用const char*的類型。
main.cpp文件內容:
#include<iostream>
#include "test1.h"
#include "Shared_lib.h"
using namespace std;
int main()
{
int i;
cin >> i;
if (i == 1)
{
printTest1();
}
else
{
typedef void (*print)();
Shared_lib shared_lib("test2.dll");
print p = (print)shared_lib.getFunc("printTest2");
if (p != nullptr)
{
p();
}
}
return 0;
}
因為main.cpp中使用了test.h,所以需要在DLL_TEST項目中添加這個h文件所在的目錄,也要添加test1項目生成的lib目錄與test1.lib。



test1.h文件代碼如下:
#pragma once #include<iostream> using namespace std; __declspec(dllexport) void printTest1();
需要添加__declspec(dllexport),否則編譯完成不會生成.lib文件。
test1.cpp文件代碼如下:
#include "test1.h"
void printTest1()
{
cout << "printTest1" << endl;
}
test2.h文件代碼如下:
#pragma once #include<iostream> using namespace std; extern "C" __declspec(dllexport) void printTest2();
前面要加extern “C”的關鍵字,按照C程序來編譯這一部分代碼。
test2.cpp文件代碼如下:
#include "test2.h"
void printTest2()
{
cout << "printTest2" << endl;
}
