Use a pure C function pointer to call C ++ class member functions

Source: Internet
Author: User

Starting point: I happened to see a scenario where I needed to call C ++ using C code. I didn't find a solution on google, so I recorded this requirement, today I read GECKO's NPAPI code and found a way

Principle: The static members of the class are published to the outer layer as shared, so they do not have the member function address, so it can be used to provide an opportunity for us to call the class member functions.
You can call the specific action of this pointer internally by passing the pointer of the class in the static member function.

This solves the problem that C function pointers cannot call C ++ class member functions.


The following is an instance:

# Include <iostream>

Class C;

Struct test {
Char (* a) (C *);
};

Class C {
Public:
Static char xxx (C * com_on ){
Return com_on-> _ xxx ();
}
Char _ xxx (){
Std: cout <"hei! _ Xxx called "<std: endl;
Return 'a ';
}
};

Int main (){
Test x;
C hei;
X. a = hei. xxx;
X. a (& hei );
Return 0;
}

The second method is to use the youyuan function. Do you understand the specific principle? The above code is not changed to the void * type. I think you can understand it. If you don't understand it, the following should be clear enough:


# Include <iostream>

Class C;

Struct test {
Char (* a) (void *);
};
Char xxx (void *);

Class C {
Public:
Friend char xxx (void * com_on );
Char _ xxx (){
Std: cout <"hei! _ Xxx called "<std: endl;
Return 'a ';
}
};
Char xxx (void * com_on ){
Return (C *) com_on)-> _ xxx ();
}
Int main (){
Test x;
C hei;
X. a = xxx;
X. a (& hei );
Return 0;
}

Author: "white bones of Angels"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.