c++导出动态库

一、c++风格

DllExport.h

#pragma once
#include <string>


#ifdef API_CTRL_EXPORT
    #ifdef _WIN32
        #define API_CTRL __declspec(dllexport)
    #else
        #define API_CTRL __attribute__((visibility("default")))
    #endif
#else
    #ifdef _WIN32
        #define API_CTRL __declspec(dllimport)
    #else
        #define API_CTRL 
    #endif
#endif



namespace API_C_PLUS {
class API_CTRL ApiTest
{
public:
    void DoTest();
    std::string GetData();
};

}

DllEXport.cpp

#define API_CTRL_EXPORT
#include "DllExport.h"


namespace API_C_PLUS {
void ApiTest::DoTest()
{
    printf("This is a dll export test\n");
}

std::string ApiTest::GetData()
{
    return std::string("Data from dll import");
}

}

二、c风格

CApiExport.h

#pragma once
#include <string>


#ifdef API_CTRL_EXPORT_C
    #ifdef _WIN32
        #define API_CTRL_C __declspec(dllexport)
    #else
        #define API_CTRL_C __attribute__((visibility("default")))
    #endif
#else
    #ifdef _WIN32
        #define API_CTRL_C __declspec(dllimport)
    #else
        #define API_CTRL_C 
    #endif
#endif



namespace API_C{
API_CTRL_C void DoTest();

API_CTRL_C std::string GetData();
}


CApiExport.cpp

#define API_CTRL_EXPORT_C
#include "CApiExport.h"


namespace API_C {
void DoTest()
{
    printf("This is a dll export test\n");
}

std::string GetData()
{
    return std::string("Data from dll import");
}

}

三、测试

#include <iostream>
#include "../DllEXport/DllExport.h"
#include "../DllEXport/CApiExport.h"


// set lib path
#pragma comment(lib, "../Debug/DllEXport.lib")
int main()
{
    std::cout << "-------------Test c++ class export-------------\n";
    // test c++ class api
    {
        API_C_PLUS::ApiTest objTest;
        objTest.DoTest();

        std::string strData(objTest.GetData());
        std::cout << "Data: " << strData << "\n";
    }

    std::cout << "\n\n-------------Test c++ class export-------------\n";
    // test c api
    {
        API_C::DoTest();
        std::string strData(API_C::GetData());
        std::cout << "Data: " << strData << "\n";
    }

    getchar();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值