之前偶然碰見一個需要使用C代碼調(diào)用C++的成員函數(shù)的場景,于是記錄下了這個需求,今天看了GECKO的NPAPI代碼,找到一種方式
原理:類的static成員是作為共享的方式被發(fā)布給外層的,所以不具有成員函數(shù)地址,因此它可以用來為我們轉(zhuǎn)彎的調(diào)用類的成員函數(shù)提供一個機會。
在static成員函數(shù)中傳遞類本身的指針,就可以在內(nèi)部調(diào)用這個指針的具體動作(做一下強制轉(zhuǎn)換)。
由于static成員函數(shù)本身的作用域是屬于類的public/protected的,所以它既能被外部調(diào)用,也能直接使用類內(nèi)部的/public/protected/private成員。
這解決了不能通過C的函數(shù)指針直接調(diào)用C++的類普通public成員函數(shù)的問題。
以下是一個實例:
#include <iostream>
struct test
{
char (*cptr_func)(void *);
};
class C
{
public:
static char cpp_func(void *vptr){
//針對這個對象調(diào)用他的成員函數(shù)
return static_cast<C*>(vptr)->_xxx();
}
char _xxx(){
std::cout<<"hei! _xxx called"<<std::endl;
return 'a';
}
};
int main()
{
struct test c_obj;
class C cpp_obj;
c_obj.cptr_func = C::cpp_func;
std::cout<< c_obj.cptr_func(&cpp_obj) <<std::endl;
return 0;
}
由此我又想到使用友元函數(shù),看下面的代碼就明白了
#include <iostream>
struct test
{
char (*cptr_func)(void *);
};
char cpp_friend_func(void*);
class C
{
friend char cpp_friend_func
(void *vptr);
public:
char _xxx(){
std::cout<<"hei! _xxx called"<<std::endl;
return 'a';
}
};
char
cpp_friend_func
(void *com_on) //friend function have the ability of calling class public/private/protected member functions
{
return static_cast<C*>(vptr)->_xxx();
}
int main()
{
struct test c_obj;
class C cpp_obj;
c_obj.cptr_func = cpp_friend_func;
std::cout<< c_obj.cptr_func(&cpp_obj) <<std::endl;
return 0;
}