使用純C函數指針調用C++的類成員函數


使用純C函數指針調用C++的類成員函數

之前偶然碰見一個需要使用C代碼調用C++的成員函數的場景,於是記錄下了這個需求,今天看了GECKO的NPAPI代碼,找到一種方式
原理:
類的static成員是作為共享的方式被發布給外層的,所以不具有成員函數地址,因此它可以用來為我們轉彎的調用類的成員函數提供一個機會。
在static成員函數中傳遞類本身的指針,就可以在內部調用這個指針的具體動作(做一下強制轉換)。
由於static成員函數本身的作用域是屬於類的public/protected的,所以它既能被外部調用,也能直接使用類內部的/public/protected/private成員。

這解決了不能通過C的函數指針直接調用C++的類普通public成員函數的問題。


以下是一個實例:
#include <iostream>

struct test
{
    char (*cptr_func)(void *);
};

class C
{
public:
    static char cpp_func(void *vptr){
//針對這個對象調用他的成員函數
        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;
}
由此我又想到使用友元函數,看下面的代碼就明白了
#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;
}

 


轉載自http://www.cppblog.com/TianShiDeBaiGu/archive/2011/09/09/baigu.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM