zoukankan      html  css  js  c++  java
  • 《内存对齐与回调函数参数》

    在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
  • 相关阅读:
    HTML5 重力感应效果,实现摇一摇效果
    WEB 移动端 CSS3动画性能 优化
    jquery 插件封装模板
    textarea 提交到数据库的内容,输出到 html 中显示正常的格式
    js根据银行卡号判断属于哪个银行,并返回银行缩写及银行卡类型
    微信小程序如何引用iconfont图标
    nodejs: express basic
    javascript设计模式:适配器模式
    javascript设计模式:装饰者模式
    javascript设计模式:代理模式
  • 原文地址:https://www.cnblogs.com/DeanWang/p/7087020.html
Copyright © 2011-2022 走看看