c++ 类文件的动态库生成及调用例子

来源:互联网 发布:手机淘宝应用未安装 编辑:程序博客网 时间:2024/06/05 20:55

首先,创建一个简单的类,类头文件的名称与项目工程的名称应该一致,
控制台项目工程名:testClass,要导出的类文件名称也应为:testClass.h,这样创建后会生成名称一致的testClass.lib,testClass.dll.

#ifndef TEST_CLASS_H_#define TEST_CLASS_H_#include <iostream>#include <string>using namespace std;#ifdef SERVERDLL_EXPORTS#define SERVERDLL_API __declspec(dllexport)#else#define SERVERDLL_API __declspec(dllimport)#endifclass SERVERDLL_API TestClass{public:    virtual void VirtualFunction(const string& model_file, const string& trained_file, const string& mean_file);    void NormalFunction(void);};SERVERDLL_API void func(void);#endif
#include "testClass.h"void TestClass::VirtualFunction(const string& model_file, const string& trained_file, const string& mean_file){    std::cout << "modelfile=" << model_file << std::endl;    std::cout << "modelfile=" << trained_file << std::endl;    std::cout << "modelfile=" << mean_file << std::endl;}void TestClass::NormalFunction(void){    std::cout << "this is NormalFunction()!" << std::endl;    return;}void func(void){    cout << "xixihaha" << endl;    return;}

右键属性-》配置属性=》常规=》配置类型选为(动态库(.dll)),目标文件扩展名:.dll。
预处理定义加上:SERVERDLL_EXPORTS
选择:Relase x64 或者Debug x64平台。调用的项目也应该与生成动态库的平台保持一致。点击生成即可得到testClass.lib,testClass.dll.
第二部分:dll的调用。
新建一个测试工程如testClassdll,加入头文件testClass.h

#ifndef TEST_CLASS_H_#define TEST_CLASS_H_#include <iostream>#include <string>using namespace std;#ifdef SERVERDLL_EXPORTS#define SERVERDLL_API __declspec(dllexport)#else#define SERVERDLL_API __declspec(dllimport)#endifclass SERVERDLL_API TestClass{public:    virtual void VirtualFunction(const string& model_file, const string& trained_file, const string& mean_file);    void NormalFunction(void);};SERVERDLL_API void func(void);#endif

main.cpp代码如下:

#include "testClass.h"#include <iostream>//#include <Windows.h>using namespace std;#pragma comment(lib,"F:\\VcProject\\2017\\testClassdll\\testClassdll\\testClass.lib")int main(){    TestClass object;    std::string model_file("C:\\Caffedllcpu\\MultiClassificationChen\\model\\deploy.prototxt");    std::string trained_file("C:\\Caffedllcpu\\MultiClassificationChen\\model\\Train.caffemodel");    std::string mean_file("C:\\Caffedllcpu\\MultiClassificationChen\\model\\MeanFile.binaryproto");    object.NormalFunction();    object.VirtualFunction(model_file, trained_file, mean_file);    func();    return 0;}

连接器输入:testClass.lib

0 0
原创粉丝点击