C++桥接模式封装C函数

2020-11-04  本文已影响0人  FredricZhu

程序目录如下


图片.png

代码如下,
main.cpp

#include "utils/utils.hpp"

using namespace utils;

int main() {
    utils::FileSharedPtr ptr("1.log", "r");    
    std::string s;
    int n;
    while((n=ptr.Read(s, utils::BUFFER_SIZE)) != utils::F_EOF) {
        std::cout << s;
    }
    std::cout << std::endl;
    system("pause");
    return 0;
}

utils.hpp

#ifndef UTILS_HPP
#define UTILS_HPP

#include "file_shared_ptr.hpp"




namespace utils {
    static const int BUFFER_SIZE = 50;
    static const int F_EOF = 0;
};

#endif

file_shared_ptr.hpp

#ifndef FILE_SHARED_PTR_HPP
#define FILE_SHARED_PTR_HPP

#include <boost/shared_ptr.hpp>
#include <boost/format.hpp>
#include <iostream>
#include <windows.h>
using namespace std;
using namespace boost;

namespace utils {
    class FileSharedPtr {
        private:
            class impl; // 前向声明
            boost::shared_ptr<impl> pimpl;
        public:
            FileSharedPtr(std::string name, std::string mode);
            int Read(std::string& s, size_t size);
    };
};

#endif

file_shared_ptr.cpp

#include "file_shared_ptr.hpp"


namespace utils {
    class FileSharedPtr::impl {
        private:
            impl(const impl &){}
            impl& operator=(const impl&){return *this;}
            FILE* f;
        
        public:
            impl(std::string name, std::string mode) {
                f = fopen(name.c_str(), mode.c_str());
            }

            ~impl() {
                int result = fclose(f);
                std::cout << "invoke FileSharedPtr::impl 析构函数, result= " << result << std::endl;
            }

            int Read(std::string& s, size_t size) {
                char data[size+1];
                int res = fread(data, 1, size, f);
                data[size] = '\0';
                s = boost::str(boost::format(data));
                return res; 
            }
    };

    FileSharedPtr::FileSharedPtr(std::string name, std::string mode): pimpl(new FileSharedPtr::impl(name,mode)) {}
    int FileSharedPtr::Read(std::string& s, size_t size) {
        return pimpl->Read(s, size);
    }
};

程序输出如下,
还是最后一句析构是精华


图片.png
上一篇 下一篇

猜你喜欢

热点阅读