Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extern "C" for member static callback function

I want to provide a callback function for code written in Haskell (GHC). It uses GCC C-compiler-like function types to export/import functionality and interoperate at runtime with my code.

I have to provide a callback function, which in fact accept this pointer to the class and just call its method:

struct C
{
    int f(int i) { ; }
    static int f_callback(void * self, int i)
    {
        static_cast< C * >(self)->f(i);
    }
};

Logically f_callback is a part of class C, so I placed it into the corresponding namespace scope.

But I worry about should I use extern "C" language specification (calling convention is matters here, not name mangling)? It is possible to declare and define extern "C" function in plain namespace, there are a couple of special rules for extern "C" functions defined with the same name in different namespaces, but there is no distinction between namespace of class scope and simple namespace one.

Is it possible to define static extern "C" function into class scope?

like image 578
Tomilov Anatoliy Avatar asked Sep 21 '17 06:09

Tomilov Anatoliy


1 Answers

The external callback is by design not linked to a specific class.

Making it a static class member is perhaps nice according to the internals of your code, but it misrepresents the reality.

I'd therefore advise to make it an independent extern "C" function. This avoids misunderstanding and highlights assumptions (for example that self is assumed to be a C but could in reality be something else). If f() is public, all this will be very clean. If it would be private, you'd need to make your callback a friend and this tight coupling would be again highlighted.

The wrapper alternative would just add a redundant middleman to come to the same result.

like image 125
Christophe Avatar answered Nov 05 '22 02:11

Christophe