《内存对齐与回调函数参数》

在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 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/DeanWang/p/7087020.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值