Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You cannot directly pass a pointer to a C++ functor object as a function pointer to C code (or even to C++ code).</p> <p>Additionally, to portably pass a callback to C code it needs to be at least declared as an <code>extern "C"</code> non-member function. At least, because some APIs require specific function call conventions and thus additional declaration modifiers.</p> <p>In many environments C and C++ have the same calling conventions and differ only in name mangling, so any global function or static member will work. But you still need to wrap the call to <code>operator()</code> in a normal function.</p> <ul> <li><p>If your functor has no state (it is an object just to satisfy some formal requirements etc):</p> <pre><code>class MyFunctor { // no state public: MyFunctor(); int operator()(SomeType &amp;param) const; } </code></pre> <p>you can write a normal extern "C" function which creates the functor and executes its operator().</p> <pre><code>extern "C" int MyFunctorInC(SomeType *param) { static MyFunctor my_functor; return my_functor(*param); } </code></pre></li> <li><p>If your functor has state, eg:</p> <pre><code>class MyFunctor { // Some fields here; public: MyFunctor(/* some parameters to set state */); int operator()(SomeType &amp;param) const; // + some methods to retrieve result. } </code></pre> <p><strong>and</strong> the C callback function takes some kind of user state parameter (usually void *):</p> <pre><code>void MyAlgorithmInC(SomeType *arr, int (*fun)(SomeType *, void *), void *user_state); </code></pre> <p>you can write a normal extern "C" function which casts its state parameter to your functor object:</p> <pre><code>extern "C" int MyFunctorInC(SomeType *param, void *user_state) { MyFunctor *my_functor = (MyFunctor *)user_state; return (*my_functor)(*param); } </code></pre> <p>and use it like this:</p> <pre><code>MyFunctor my_functor(/* setup parameters */); MyAlgorithmInC(input_data, MyFunctorInC, &amp;my_functor); </code></pre></li> <li><p>Otherwise the only normal way to do it (normal as in "without generating machine code at runtime" etc.) is to use some static (global) or thread local storage to pass the functor to an extern "C" function. This limits what you can do with your code and is ugly but will work.</p></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload