DeanWang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

在C++中,有时候当使用函数指针做回调的时候,函数的参数需要一并传入,而函数的各个参数可能就要保证内存对齐,使得在读取使用的时候能够读到正确的数据;

比如在VS里面针对各个版本的工程中,可以定义宏:

#defined PLATFORM_WIN32 || defined PLATFORM_NN_WIN
#define ALIGN_PC( bytes ) __declspec(align(bytes))
#define ALIGN_PS3( bytes )
#define ALIGN_X360( bytes )
#define ALIGN_NX( bytes )
#endif

而一个class的成员变量存储函数回调指针和参数:

ALIGN_PC(16) ALIGN_NX(16) ALIGN_X360(16) uint8_t m_Param[ PARAM_SIZE ] ALIGN_PS3( 16 );
TaskFunction * m_Function;

其中:

typedef unsigned char uint8_t;

在调用的时候,形式即可以为:

bool res = m_Function( this->m_Param );

而具体关于函数指针的类型相关的定义可以为:

typedef bool TaskFunction( const void* a_Param );

#if defined(ENABLE_PIX) || (defined(USE_NEW_WORKER_THREADS) && defined(NEW_WORKER_THREADS_DEBUG))//some macro

struct TaskFunctionParameterStruct
{
    TaskFunctionParameterStruct( TaskFunction* a_Function, const char * a_Name  )
        : m_Function( a_Function )
        , m_Name( a_Name )
    {
    }
    
    operator TaskFunction* () const
    {
        return m_Function;
    }

    mutable TaskFunction* m_Function;    
    mutable const char* m_Name;

    
};

#define TASK_FUNCTION( F ) TaskFunctionParameterStruct( F, #F )
typedef const TaskFunctionParameterStruct& TaskFunctionParameter;
#else
#define TASK_FUNCTION( F ) F
typedef TaskFunction* TaskFunctionParameter;
#endif


//then:
//assign function pointer code

bool xxx::UpdateFunctionCallBack(const void* a_UserData)
{
    return false;
}

TaskFunctionParameter a_Funcion = UpdateFunctionCallBack;

m_Function = a_Function;
m_Param = &structParamter;//can store one struct pointer, this struct store the paramters

 

posted on 2017-06-27 20:36  DeanWang  阅读(431)  评论(0编辑  收藏  举报