详解如何利用C++实现一个反射类

2023-03-09 17:03:52 反射 利用 详解

代码环境为vscode + CMake + GCC 8.1.0

首先,如何才能做到给我一个名字我就能拿到这个对象的这个值,也是比较难的一个地方,方法如下

#define OFFSET(className,fieldName) (size_t)&(((className*)0)->fieldName)

这个能够得到该成员变量与该对象的偏移量,之后根据这个偏移量来获取成员的值

正题开始

首先这个反射类应该只有一个,要不然反射就会变得很混乱,这一个反射对象,那里一个反射对象。所以应该将该反射类变为一个单例。全局内只允许出现一个。单例类如下:

Singleton.h

#pragma once
#include "Singleton.h"
#ifndef _SINGLETON_
#define _SINGLETON_
#include "Util.h"

NAME_SPACE_START(myUtil)
//单例模式
template<typename T>
class Singleton{
public:
    static T* Instance(){
        if(m_instance==nullptr){
            m_instance = new T();
        }
        return m_instance;
    }
private:
    Singleton();
    Singleton(const Singleton<T>&);
    ~Singleton();
    Singleton<T>& operator=(const Singleton<T>&);

private:
    static T* m_instance;
};

template<typename T>
T* Singleton<T>::m_instance=nullptr;

#define SINGLETON_DECLARE(className)                    \
        friend class Singleton<className>;              \
        className(){};                                  \
        className(const className&){};                  \
        ~className(){};                                 \
        className& operator=(const className&);

NAME_SPACE_END()
#endif //!_SINGLETON_

我在这个头文件中写了一个单例声明SINGLETON_DECLARE,只要将这个声明放到私有部分就行了,这个类就变为一个单例类了。

反射类

如何才能做到反射呢,应该在这个反射类中保存注册表,传入了对应的类名,返回对应的信息,然后使用基类实现对应的方法即可。代码如下:

Reflex.h

#pragma once
#include "Util.h"
#include <cstdint>
#include <vadefs.h>
#include <vector>
#include <functional>
#ifndef _REFLEX_
#define _REFLEX_

NAME_SPACE_START(myUtil)
#include "Singleton.h"
#include <map>
#include <string>

//因为编译器不支持类模板和实现分开写,所以放到一起了
class Field;
class Reflex;
class RObject{
public:
    RObject(){}
    virtual ~RObject(){}
    std::string _className;

    template<typename T>
    T get(const std::string& fieldName);

    template<typename T>
    void set(const std::string& fieldName, const T& fieldValue);

    void Call(const std::string& methodName);
    template<typename T,typename... Args>
    T Call(const std::string& methodName, Args... args);
};

typedef RObject* (*construct)(void);

//使用方法,使用REGISTER_REFLEX注册,然后直接使用createClass即可
class Reflex{
    SINGLETON_DECLARE(Reflex)
public:
    void ReflexRegister();
    RObject* createClass(const std::string& className);
    void RegisterClass(const std::string& className, construct constructMethod);

    void RegisterField(const std::string& className, const std::string& FieldName, const std::string& FieldType, const size_t& offset);
    void RegisterMethod(const std::string& className, const std::string& methodName, const uintptr_t& lpMethod);
    template<typename T>
    T getClassField(void* originPos, const std::string& className, const std::string& fieldName);
    template<typename T>
    void setClassField(void* originPos, const std::string& className, const std::string& fieldName, const T& fieldValue);

    uintptr_t getClaSSMethod(const std::string& className, const std::string& methodName);
private:
    std::map<std::string, construct> m_classMap;
    std::map<std::string, std::map<std::string, Field>> m_fieldMap;
    std::map<std::string, std::map<std::string, uintptr_t>> m_methodMap;
};

//仅仅用来在reflex中注册使用
class RegisterClass{
public:
    RegisterClass(const std::string& className,construct constructMethod)
    {
        Reflex* factory = myUtil::Singleton<Reflex>::Instance();
        factory->RegisterClass(className, constructMethod);
    }
    RegisterClass(const std::string& className,const std::string& fieldName,const std::string& fieldType,const size_t& offset)
    {
        Reflex* factory = myUtil::Singleton<Reflex>::Instance();
        factory->RegisterField(className, fieldName, fieldType, offset);
    }
    RegisterClass(const std::string& className,const std::string& methodName,const uintptr_t& lpMethod)
    {
        Reflex* factory = myUtil::Singleton<Reflex>::Instance();
        factory->RegisterMethod(className, methodName, lpMethod);
    }
};

class Field{
private:
    std::string m_fieldType{""};
    //std::string m_fieldName{""};
    size_t m_offset{0};
public:
    Field(){}
    Field(const std::string& fieldType,const size_t& offset):
        m_fieldType(fieldType),m_offset(offset){}
    ~Field(){}
    
    inline std::string getFieldType(){return m_fieldType;}
    //inline std::string getFieldName(){return m_fieldName;}
    inline size_t getOffSet(){return m_offset;}

    inline void setFieldType(const std::string& type){ m_fieldType = type;}
    //inline void setFieldName(const std::string& name){ m_fieldName = name;}
    inline void setOffSet(const size_t& offset){ m_offset = offset;}
};

class Method{
public:
    Method(){}
    Method(const std::string& name,const std::uintptr_t& method):
        methodName(name),lpMethod(method){}
    ~Method(){}
    inline void setMethodName(const std::string& name) { methodName = name;}
    inline void setLpMethod(const uintptr_t& lp) { lpMethod = lp;}
    inline std::string getMethodName(){return methodName;}
    inline uintptr_t getLpMethod(){return lpMethod;}
private:
    std::string methodName{""};
    std::uintptr_t lpMethod{0};
};


#define REGISTER_REFLEX(className)                                      \
        RObject* construct##className()                                 \
        {                                                               \
            RObject* obj = new className();                             \
            obj->_className = #className;                               \
            return obj;                                                 \
        }                                                               \
        RegisterClass registerClass##className(#className,construct##className);

#define REGISTER_REFLEX_FIELD(className,fieldType,fieldName)            \
        RegisterClass registerClass##className##fieldType##fieldName(#className,#fieldName,#fieldType,OFFSET(className,fieldName));

#define REGISTER_REFLEX_METHOD(className,methodName)                    \
        std::function<void(className)> className##methodName = &className::methodName;\
        RegisterClass registerClass##className##method(#className,#methodName,(std::uintptr_t)&className##methodName);

#define REGISTER_REFLEX_METHOD_ARGS(className,methodName,returnType,...)                    \
        std::function<returnType(className,##__VA_ARGS__)> className##methodName = &className::methodName;\
        RegisterClass registerClass##className##method##returnType(#className,#methodName,(std::uintptr_t)&className##methodName);

template<typename T>
T RObject::get(const std::string &fieldName)
{
    Reflex* factory = myUtil::Singleton<Reflex>::Instance();
    return factory->getClassField<T>(this, _className, fieldName);
}

template<typename T>
void RObject::set(const std::string &fieldName, const T &fieldValue)
{
    Reflex* factory = myUtil::Singleton<Reflex>::Instance();
    factory->setClassField(this, _className, fieldName, fieldValue);
}

void RObject::Call(const std::string& methodName)
{
    Reflex* factory = myUtil::Singleton<Reflex>::Instance();
    std::uintptr_t temp = factory->getClassMethod(_className, methodName);
    if (temp == 0) return;
    typedef std::function<void(decltype(this))> class_method;
    class_method* method = (class_method*)temp;
    (*method)(this);
}

template<typename T,typename... Args>
T RObject::Call(const std::string& methodName,Args... args)
{
    Reflex* factory = myUtil::Singleton<Reflex>::Instance();
    std::uintptr_t temp = factory->getClassMethod(_className, methodName);
    if(temp == 0) return T();
    typedef std::function<T(decltype(this),Args...)> class_method;
    class_method* method = (class_method*)temp;
    return (*method)(this,args...);
}

RObject* Reflex::createClass(const std::string &className)
{
    if(m_classMap.find(className)==m_classMap.end()) return nullptr;
    return m_classMap[className]();
}

void Reflex::RegisterClass(const std::string &className, construct constructMethod)
{
    if(m_classMap.find(className)!=m_classMap.end()){
        throw std::exception();
        return;
    }
    m_classMap.insert(std::pair<std::string, construct>(className,constructMethod));
    m_fieldMap[className] = std::map<std::string, Field>();
    m_methodMap[className] = std::map<std::string, uintptr_t>();
}

void Reflex::RegisterField(const std::string &className, const std::string &FieldName, const std::string &FieldType, const size_t &offset)
{
    m_fieldMap[className][FieldName] = Field(FieldType,offset);
}

void Reflex::RegisterMethod(const std::string &className, const std::string &methodName, const uintptr_t &lpMethod)
{
    m_methodMap[className][methodName] = lpMethod;
}

template<typename T>
T Reflex::getClassField(void* originPos, const std::string &className, const std::string &fieldName)
{
    if(m_fieldMap.find(className) == m_fieldMap.end()){
        return T();
    }
    if(m_fieldMap[className].find(fieldName) == m_fieldMap[className].end()){
        return T();
    }
    size_t offset = m_fieldMap[className][fieldName].getOffSet();
    return *(T*)((size_t)originPos + offset);
}

template<typename T>
void Reflex::setClassField(void* originPos, const std::string &className, const std::string &fieldName, const T &fieldValue)
{
    if(m_fieldMap.find(className) == m_fieldMap.end()){
        return;
    }
    if(m_fieldMap[className].find(fieldName) == m_fieldMap[className].end()){
        return;
    }
    size_t offset = m_fieldMap[className][fieldName].getOffSet();
    *(T*)((size_t)originPos + offset) = fieldValue;
}

uintptr_t Reflex::getClassMethod(const std::string &className, const std::string &methodName)
{
    if(m_fieldMap.find(className) == m_fieldMap.end()){
        return 0;
    }
    if(m_methodMap[className].find(methodName) == m_methodMap[className].end()){
        return 0;
    }
    return m_methodMap[className][methodName];
}

NAME_SPACE_END()
#endif //!_REFLEX_

该反射类使用方法如下:

#include <iOStream>
#include <string>
#include "Util.h"
#include "Singleton.h"
#include "Reflex.h"
using namespace std;
using namespace myUtil;

class A:public RObject{
public:
    void show(){
        cout<<"hello world"<<endl;
    }
    int add(int a,int b){
        return a+b;
    }
    int m_age;
    A():m_age(10){}
};

REGISTER_REFLEX(A)
REGISTER_REFLEX_FIELD(A, int, m_age)
REGISTER_REFLEX_METHOD(A, show)
REGISTER_REFLEX_METHOD_ARGS(A, add, int,int,int)

int main(){
    Reflex* factory=Singleton<Reflex>::Instance();
    A* a=(A*)factory->createClass("A");
    cout<<a->get<int>("m_age")<<endl;
    a->set<int>("m_age", 30);
    cout << a->get<int>("m_age") << endl;
    a->Call("show");
    int b = a->Call<int,int,int>("add",1,5);
    cout << b << endl;
    A* c=(A*)factory->createClass("A");
    cout<<c->get<int>("m_age")<<endl;
    c->set<int>("m_age", 40);
    cout << c->get<int>("m_age") << endl;
    c->Call("show");
    b = c->Call<int,int,int>("add",2,5);
    cout << b << endl;
    return 0;
}

结果截图

最后讲解一下是怎么用的,见注释

//首先要使用反射的类要继承RObject
//要使用反射的类和成员方法都要声明为public
class A:public RObject{
public:
    void show(){
        cout<<"hello world"<<endl;
    }
    int add(int a,int b){
        return a+b;
    }
    int m_age;
    A():m_age(10){}
};
//这里在反射类中注册A这个类,原理是把重复工作用宏展开来替代
REGISTER_REFLEX(A)
//注册类中的成员变量,一定要先注册类再注册成员变量,原理是将成员变量与对象的偏移量保存起来,用到的时候解引用来获取值
REGISTER_REFLEX_FIELD(A, int, m_age)
//注册类的成员方法,此宏是声明没有返回值和入参的成员方法的,原理是使用function能够调用成员函数的功能,将function的地址保存到注册表中(转为uintptr_t),需要时通过传入的参数转换回来,再调用
REGISTER_REFLEX_METHOD(A, show)
//注册类的成员方法,此宏是声明有返回值和多参数的成员方法的,原理同上
REGISTER_REFLEX_METHOD_ARGS(A, add, int,int,int)

int main(){
	//在使用类时,要先获取这个全局唯一的反射对象,使用它来创建对象
    Reflex* factory=Singleton<Reflex>::Instance();
    A* a=(A*)factory->createClass("A");
    //为了能够得到准确的类型值,这里使用模板来获取
    cout<<a->get<int>("m_age")<<endl;
    //设置同获取
    a->set<int>("m_age", 30);
    cout << a->get<int>("m_age") << endl;
    //调用无参且无返回值的成员函数时使用没有模板的Call,反之使用有模板的Call
    a->Call("show");
    int b = a->Call<int,int,int>("add",1,5);
    cout << b << endl;
    return 0;
}

到此这篇关于详解如何利用c++实现一个反射类的文章就介绍到这了,更多相关C++反射类内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章