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


    在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
  • 相关阅读:
    socket server的N种并发模型
    进程、线程以及Goroutine的区别
    分布式从ACID、CAP、BASE的理论推进
    epoll的理论与IO阻塞机制
    golang面试题知识点总结
    golang中如何进行项目模块及依赖管理
    面对golang中defer,要注意什么?
    Kaggle 学习之旅
    推荐在线学习读书网站
    k8s 的 dashboard 的实践
  • 原文地址:https://www.cnblogs.com/DeanWang/p/7087020.html
Copyright © 2020-2023  润新知