C中如何調(diào)用C++函數(shù)?

字號(hào):

在C中如何調(diào)用C++函數(shù)的問(wèn)題,將 C++ 函數(shù)聲明為``extern "C"''(在你的 C++ 代碼里做這個(gè)聲明),然后調(diào)用它(在你的 C 或者 C++ 代碼里調(diào)用)。例如:
    // C++ code:
    extern "C" void f(int);
    void f(int i)
    {
     // ...
    }
    然后,你可以這樣使用 f():
    /* C code: */
    void f(int);
    void cc(int i)
    {
     f(i);
     /* ... */
     }
    當(dāng)然,這招只適用于非成員函數(shù)。如果你想要在 C 里調(diào)用成員函數(shù)(包括虛函數(shù)),則需要提供一個(gè)簡(jiǎn)單的包裝(wrapper)。例如:
    // C++ code:
    class C
    {
     // ...
     virtual double f(int);
    };
    extern "C" double call_C_f(C* p, int i) // wrapper function
    {
     return p->f(i);
    }