3

How do I get the size in bytes of function parameters? Example: void DummyFun(int64_t a, int32_t b, char c); The size in bytes is going to be 13.

I'm trying to solve this by using templates, but I'm not very good at it.

This is the contextualized code and what I tried so far:

template<typename T>
constexpr size_t getSize()
{
    return sizeof(T);
}

template<typename First, typename ... Others>
constexpr size_t getSize()
{
    return getSize<Others...>() + sizeof(First);
}

class NamelessClass
{
private:
    typedef void (*DefaultCtor)(void*);
    
    void HookClassCtor(DefaultCtor pCtorFun, size_t szParamSize);

public:
    template<typename T, typename ... Types>
    inline void HookClassCtor(T(*pCtorFun)(Types ...))
    {
        // I need the size in bytes not the count
        // HookClassCtor(reinterpret_cast<DefaultCtor>(pCtorFun), sizeof...(Types));
        
        size_t n = getSize<Types ...>();
        HookClassCtor(reinterpret_cast<DefaultCtor>(pCtorFun), n);  
    }
};

guila
  • 33
  • 5

1 Answers1

2

In C++17 you can use a fold expression:

template<typename... Others>
constexpr size_t getSize() {
    return (sizeof(Others) + ...);
}

Demo

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • Perfect! Thank you very much. – guila Nov 03 '20 at 06:11
  • @guila You're welcome! – Ted Lyngmo Nov 03 '20 at 06:22
  • 1
    @guila Just a word of caution: The `sizeof` total is most probably _not_ going to be equal to the amount of bytes that the arguments will occupy on the stack. I don't know of a portable way to calculate that. – Ted Lyngmo Nov 03 '20 at 07:17
  • 1
    Yes, the size depends on the calling convention in which the function was compiled. In some calling conventions, the values are passed in the registers, in the stack, or both. So, as long I keep track of the calling convention used, I shouldn't get problems if I'm not missing anything. But thank you for pointing me that. – guila Nov 03 '20 at 13:29
  • @guila Great! It sounds like you on top of that. I was just making sure! :) – Ted Lyngmo Nov 03 '20 at 13:29