简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM