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
  • 相关阅读:
    idea Ctrl+Alt+向下箭头 复制不起作用问题解决
    @Data 注解使用
    idea class类增加注释
    mysql 固定用户赋值数据库权限
    springboot logback 详细配置
    gitblit 增加ssh key
    uniapp内嵌H5页面和uniapp页面相互传值
    博客搬家
    反编译,java字节流 ,wirshark抓包,php转换中文
    charles 双向抓包
  • 原文地址:https://www.cnblogs.com/DeanWang/p/7087020.html
Copyright © 2011-2022 走看看