Stuart K
Stuart K

Reputation: 3282

Can I call a std::function from C?

I have some C++ code that returns a std::function. I would like to call this from some C code. Is this possible? As an example I have the following code:

typedef std::function<int(int)> AdderFunction;

AdderFunction makeAdder(int amount) {
    return [amount] (int n) {
        return n + amount;
    };
}

extern "C" {
    AdderFunction makeCAdder(int amount) {
        return makeAdder(amount);
    }
}

with clang++ -std=c++11 test.cpp it results in the following warning:

'makeCAdder' has C-linkage specified, but returns user-defined type 'AdderFunction' (aka 'function<int (int)>') which is incompatible with C

I understand why this is happening, but wondering if there is a pattern to make it possible?

Upvotes: 21

Views: 6735

Answers (5)

R Sahu
R Sahu

Reputation: 206607

The most portable method to interface between C/C++ will be to use pointers to pass data between languages and use non-member functions to make function calls.

The .h file:

#ifdef __cplusplus
extern "C" {
#endif

   // Declare the struct.
   struct Adder;

   // Declare functions to work with the struct.
   Adder* makeAdder(int amount);

   int invokeAdder(Adder* adder, int n);

   void deleteAdder(Adder* adder);

#ifdef __cplusplus
}
#endif

Implement them in a .cpp file as:

#include <functional>

typedef std::function<int(int)> AdderFunction;
struct Adder
{
   AdderFunction f;
};

AdderFunction makeAdderFunction(int amount) {
    return [amount] (int n) {
        return n + amount;
    };
}

Adder* makeAdder(int amount)
{
   Adder* adder = new Adder;
   adder->f = makeAdderFunction(amount);
   return adder;
}

int invokeAdder(Adder* adder, int n)
{
   return adder->f(n);
}

void deleteAdder(Adder* adder)
{
   delete adder;
}

Upvotes: 17

Jon Purdy
Jon Purdy

Reputation: 54979

Another solution is to split the std::function into a pointer to the closure and a pointer to the member function, and pass three things to the C function that wants to invoke the lambda:

  • The address of a C++ function that knows how to invoke the function on the closure type-safely
  • The closure pointer (unsafely cast to void *)
  • The member function pointer (hidden inside a wrapper struct and cast to void * as well)

Here’s a sample implementation.

#include <functional>
#include <iostream>

template<typename Closure, typename Result, typename... Args>
struct MemberFunctionPointer
{
    Result (Closure::*value)(Args...) const;
};

template<typename Closure, typename Result, typename... Args>
MemberFunctionPointer<Closure, Result, Args...>
member_function_pointer(
    Result (Closure::*const value)(Args...) const)
{
    return MemberFunctionPointer<Closure, Result, Args...>{value};
}

template<typename Closure, typename Result, typename... Args>
Result
call(
    const void *const function,
    const void *const closure,
    Args... args)
{
    return
        ((reinterpret_cast<const Closure *>(closure))
        ->*(reinterpret_cast<const MemberFunctionPointer<Closure, Result, Args...>*>(function)->value))
        (std::forward<Args>(args)...);
}

Sample usage from the C side:

int
c_call(
    int (*const caller)(const void *, const void *, int),
    const void *const function,
    const void *const closure,
    int argument)
{
    return caller (function, closure, argument);
}

Sample usage from the C++ side:

int
main()
{
    int captured = 5;
    auto unwrapped = [captured] (const int argument) {
        return captured + argument;
    };
    std::function<int(int)> wrapped = unwrapped;

    auto function = member_function_pointer(&decltype(unwrapped)::operator());
    auto closure = wrapped.target<decltype(unwrapped)>();
    auto caller = &call<decltype(unwrapped), int, int>;
    std::cout
        << c_call(
            caller,
            reinterpret_cast<const void *>(&function),
            reinterpret_cast<const void *>(closure),
            10)
        << '\n';
}

The reason for the wrapper struct is that you can’t cast a member function pointer to void * or any other object pointer type, not even with reinterpret_cast, so instead we pass the address of the member function pointer. You can choose to place the MemberFunctionPointer structure on the heap, e.g. with unique_ptr, if it needs to live longer than it does in this simple example.

You can also wrap these three arguments in a single structure on the C side, rather than pass them individually:

struct IntIntFunction
{
    int (*caller)(const void *, const void *, int);
    const void *function;
    const void *closure;
};

#define INVOKE(f, ...) ((f).caller((f).function, (f).closure, __VA_ARGS__))

int
c_call(IntIntFunction function)
{
    return INVOKE(function, 10);
}

Upvotes: 1

Brandon
Brandon

Reputation: 23510

The problem with this solution is when you call makeAdder with parameter values.. Couldn't solve it but I'm posting just in case someone else can..

template <typename FunctionPointerType, typename Lambda, typename ReturnType, typename ...Args>
inline FunctionPointerType MakeFunc(Lambda&& lambda, ReturnType (*)(Args...))
{
    thread_local std::function<ReturnType(Args...)> func(lambda);

    struct Dummy
    {
        static ReturnType CallLambda(Args... args)
        {
            return func(std::forward<Args>(args)...);
        }
    };

    return &Dummy::CallLambda;
}

template <typename FunctionPointerType, typename Lambda>
FunctionPointerType MakeFunc(Lambda&& lambda)
{
    return MakeFunc<FunctionPointerType, Lambda>(std::forward<Lambda>(lambda), FunctionPointerType());
}


typedef int(*AdderFunction)(int);

AdderFunction makeAdder(int amount) {
    return MakeFunc<int(*)(int)>([amount] (int n) {
        return n + amount;
    });
}

extern "C" {
    typedef int(*CAdderFunction)(int);

    CAdderFunction makeCAdder(int amount)
    {
        return makeAdder(amount);
    }
}

It works by storing the lambda a thread local std::function. Then return a pointer to a static function which will call the lambda with the parameters passed in.

I thought about using an unordered_map and keeping track of each makeAdder call but then you can't reference it from static context..

Upvotes: 0

zneak
zneak

Reputation: 138061

It's not possible to call a std::function from C, because C doesn't support the language features that are required. C doesn't have templates, access modifiers, callable objects, virtual methods, or anything else that std::function could use under the hood. You need to come up with a strategy that C can understand.

One such strategy is to copy/move your std::function to the heap and return it as an opaque pointer. Then, you would provide another function through your C++ interface that takes that opaque pointer and calls the function that it contains.

// C side
struct function_opaque;
int call_opaque(struct function_opaque*, int param);

// C++ side
extern "C" {
    struct function_opaque {
        std::function<int(int)> f;
    };

    int call_opaque(function_opaque* func, int param) {
        return func->f(param);
    }
};

Of course, this comes with memory management implications.

Upvotes: 8

Ray Hamel
Ray Hamel

Reputation: 1309

You need to put the typedef inside the extern "C" block at the minimum (to get it to compile as C++). I'm not sure that will work from C, however. What will work from C is just to use plain function pointers, e.g.

extern "C" {
using AdderFunction = int(int);
// old-style: typedef int(*AdderFunction)(int);
}

Edit: If you're using an API that gives you std::function objects, you can use the std::function::target() method to obtain the (C-callable) raw function pointer it refers to.

using AdderFunction = std::function<int(int)>;
extern "C" {
using CAdderFunction = int(int);
CAdderFunction makeCAdder(int amount)
{
        return makeAdder(amount).target<CAdderFunction>();
}
}

Upvotes: 5

Related Questions