如何将元数据附加到函数?

时间:2014-11-29 16:32:03

标签: c++ metadata function-pointers

程序中是否有基于索引的表存储可执行文件中每个函数的元数据?我需要将指针附加到给定的每个函数指针;例如:

if (!HasMetadata(functionPointer)) //Something of the form ...(*)(...)
    SetMetadata(new FunctionMetadata()); //Pointer of object of some structure of data
((FunctionMetadata*)GetMetadata(functionPointer))->Counter++;

注意:我考虑过使用key / value类型的对象;我不能,因为我有超过3000个功能,可能所有功能都需要在表中。如果我没有3000多个函数,那么我会手动考虑为每个函数添加静态值。

1 个答案:

答案 0 :(得分:-1)

C ++没有附加到函数,类或实例的内部元数据。但是,有几个可用的库,通过一些规则,允许您向各种事物添加元数据。请参阅this stackoverflow问题等。

为了您的目的,在函数指针及其元数据之间建立一种全局映射就足够了。例如,

// we'll use a generic function pointer as the key type for functions.  Note that things will 
// be somewhat trickier should you want to work with virtual functions or instance 
//members.

typedef void(*)() FunctionPtr;

static std::map<FunctionPtr, Metadata *> gFunctionMetadata;

Metadata *GetMetadata(FunctionPtr functionPtr){
   return gFunctionMetadata[functionPtr];
}

更漂亮的解决方案当然是拥有一个包含地图并提供访问元数据的方法的单例类(MetadataManager或其中一类)。