1

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?

10
  • 1
    I think you'll need to provide a subset of the functionality in the C API. When I've done similar things I've just picked the most important things first and made wrapper functions and wrapper types that only support a very specific subset of everything the real C++ functions could handle. Commented Dec 21, 2021 at 17:32
  • create dll/so and access these functions from there Commented Dec 21, 2021 at 17:33
  • 2
    You can declare C-compatible functions to call your template. Like extern "C" void foo_int(int v) { foo(v); }. Commented Dec 21, 2021 at 17:42
  • 1
    @MarcosAlvarez "It seems like C has fairly nice support for variadic functions as well" - yes, however C variadic functions and C++ variadic templates are VERY different beasts. A C++ variadic template can call a C variadic function, but I don't think the reverse is possible since the C function doesn't know what it is called with in order to populate the template parameters. Commented Dec 21, 2021 at 18:05
  • 1
    @TedLyngmo I agree. However, that is a business decision that I have no control over. The problem is solved though. The wrapper may have a tiny bit of overhead, but it is not a deal breaker. Commented Dec 22, 2021 at 14:07

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.