Home > Enterprise >  Compatibility layer in C to access template functions from C
Compatibility layer in C to access template functions from C

Time:12-27

I have some code implemented in template variadic functions that uses modern c 17 features. Being templates, they are implemented in the .h files.

// .H FILE
template <typename... T>
inline constexpr void foo(const T& ...values){
    // Do stuff
}

Is there a way to create a compatibility layer that would allow users to access this functions from C?

CodePudding user response:

The way I actually solved may not be valid to all particular cases!! I found that trying to pass arguments directly to a c variadic function was not possible (to the best of my knowledge). Instead, a void vector would be passed, and the results will not be the ones expected. In this case, stringifying the c input, and passing it to the c function worked just fine.

#ifdef __cplusplus
extern "C" {
#endif
    void cfoo(const char * fmt, ...)
    {
        va_list args
        va_start(args, fmt);
        char str[1024];
        vsprintf(str, fmt, args);
        cpp::foo(str); // My c   function
        va_end(args);
    }
#ifdef __cplusplus
}
#endif
  • Related