zoukankan      html  css  js  c++  java
  • 使用纯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
  • 相关阅读:
    CPU深度学习模型推理性能抖动问题
    深度学习推理性能优化
    Winograd Convolution 推导
    Res-Family: From ResNet to SE-ResNeXt
    CPU二则
    CPU TFLOPS 计算
    深度学习专题
    计算系统中互联设备Survey
    深度学习框架演进史
    天池医疗AI大赛支持有感
  • 原文地址:https://www.cnblogs.com/wanzaiyimeng/p/6872939.html
Copyright © 2011-2022 走看看