Passing a C++ classfunction pointer to a C function

Me and my colleagues are working on a project right now, where we are supposed to connect our C++ program to a C program we haven't written.

More specific: we "just" have to call a C function with serveral parameters.
The problem is now, that 3 parameters have to be function pointers to functions already existing in our C++ code and which are all functions of the same class...

How are we able to declare/cast/wrap/etc those pointers?

We already tried it for hours without success.
Our code is furthermore too complex to rewrite it in C...


We are thankful for any ideas :-)

which are all functions of the same class

so are they member functions?

A C function can accept a pointer to a non-member function or to a static member function, but it can't accept a pointer to a non-static member function (such pointer doesn't even hold an address)
ok i will try a workaround
> ok i will try a workaround

Wrap the call inside a free function with C linkage.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

extern "C"
{
    typedef void call_back( const void*, int ) ;

    void c_fun( call_back function, const void* arg1 )
    {
        for( int i = 0 ; i < 4 ; ++i ) function( arg1, i ) ;
    }
}

struct A
{
    void foo( int value ) const 
    { std::cout << "void A::foo(int) const - value == " << value << '\n' ; }
};

extern "C"
{
    void call_A_foo( const void* This, int v ) 
    { static_cast< const A* >( This )->foo(v) ; }
}

int main()
{
    A a ;
    c_fun( call_A_foo, &a ) ;
}

http://ideone.com/RwGojD
You need to implement a C API which has functions which call on to the C++ functions.

Andy
Last edited on
Topic archived. No new replies allowed.