C++ Reflection简单实现

记录成员变量相对于class/struct的offset和size, 再根据实例指针计算出内存地址


#include 
#include 
#include 
#define REFLEX_PROPERTY(obj,name)

using namespace std;

//属性信息记录
struct PropertyInfo
{
	const char* name;
	int offset;
	int size;
	PropertyInfo(const char* in_name, int in_offset,int in_size)
	{
		name = in_name;
		offset = in_offset;
		size = in_size;
	}
	PropertyInfo()
		:name("")
		,offset(0)
		,size(0)
	{

	}
};

class ReflectObj;
template
void AddProperty( ReflectObj* owner, T* property, const char* name )
{
	PropertyInfo newProperty =  PropertyInfo(name, (char*)(property) - (char*)owner, sizeof(T));
	owner->m_info.push_back(newProperty);
}

template
void SetProperty(ReflectObj* owner, const char* name, T value)
{
	for (std::vector::iterator it = owner->m_info.begin(); it != owner->m_info.end(); ++it)
	{
		if ( !strcmp(it->name,name) )
		{
			memcpy( (char*)owner + it->offset, &value, sizeof(T));
		}
	}
}

class ReflectObj
{
public:
	void Describle()
	{
		AddProperty(this, &name, "name");
		AddProperty(this, &id, "id");
	}
	int GetId(){return id;}
	char* GetName()
	{
		return name;
	}
	ReflectObj(char* in_name,int in_id)
		:name(in_name)
		,id(in_id)
	{

	}
private:
	char* name;
	int id;
public:
	std::vector m_info;
};

你可能感兴趣的:(C/C++)