1. 程式人生 > 其它 >C++關於使用動態庫類的一些測試

C++關於使用動態庫類的一些測試

C++對動態庫的測試

場景:

需要使用一個類,這個類在動態庫裡面,而這個靜態庫有兩個版本。

我們自己寫程式碼模擬一下這種情況。

版本一:

//標頭檔案
#pragma once

#ifndef BUILDING_DLL
#define DLLIMPORT __declspec(dllexport)
#else
#define DLLIMPORT __declspec(dllimport)
#endif
#include<iostream>
using namespace std;
class DLLIMPORT Person
{
public:
	void print();
	void setId(int ida);
	void setName(string names);
	int getId();
	string getName();
private:
	int id;
	string name;
};
//原始檔
#include "person.h"

void DLLIMPORT Person::print()
{
	cout << "this is project1's print" << endl;
}
void DLLIMPORT Person::setId(int ida)
{
	id = ida;
}
void DLLIMPORT Person::setName(string names)
{
	name = names;
}
int DLLIMPORT Person::getId()
{
	return id;
}
string DLLIMPORT Person::getName()
{
	return name;
}

編譯成了lib和dll檔案。

為了讓別人使用,需要提供標頭檔案、lib檔案和dll檔案。

版本二:

//標頭檔案
#pragma once

#ifndef BUILDING_DLL
#define DLLIMPORT __declspec(dllexport)
#else
#define DLLIMPORT __declspec(dllimport)
#endif
#include<iostream>
using namespace std;
class DLLIMPORT Person
{
public:
	void printTwo();
private:
	int id;
	string name;
};
//原始檔
#include "person.h"

void DLLIMPORT Person::printTwo()
{
	cout << "this is project2's print printTwo" << endl;
	id++;
}

生成檔案都是一樣的,類名一樣,成員也一樣,只是函式變化。

為了讓我們使用這個類時可以使用所有的函式。對於這種函式,我們可以直接修改類定義即可。

person.h

#include<iostream>
using namespace std;
class Person
{
public:
	void print();
	void setId(int ida);
	void setName(string names);
	int getId();
	string getName();
	void printTwo();
private:
	int id;
	string name;
};

main.cpp

#include "person.h"
#include<iostream>
using namespace std;
int main()
{
	Person p;
	p.setId(7);
	p.print();
	p.printTwo();
	cout << p.getId()<<endl;
	system("pause");
}

需要注意的是,需要注意兩個版本庫的重名問題。

方案:咱也不懂lib裡面是什麼,只知道里面有動態庫的名稱,那就暴力一點。

比如本來專案是dlltwo,生成dlltwo.lib和 dlltwo.dll

現在有兩套同名的檔案,我們選擇其中一套修改名稱即可。比如把第一套改成dllttt.lib和dllttt.dll

僅僅改檔名稱,還是不夠的,還需要改dllttt.lib裡面的內容。這個好像沒有捷徑,直接fopen開啟檔案。

暴力搜尋,把所有的dlltwo.dll改成dllttt.dll,注意和你修改的檔名稱對應,還有長度一致。

這樣,就可以實現同時使用兩個版本的動態庫了。這只是針對多一個函式、少一個函式的情況。