How to use c language to call a dynamic link library made of c ++ and a dynamic link library

Source: Internet
Author: User

How to use c language to call a dynamic link library made of c ++ and a dynamic link library

How to call the dynamic link library so file made by C ++ in C Language
If you have a dynamic link library made by c ++. so file, and you only have some declaration of related classes, so how do you use c to call it? Don't worry. This article uses a small example to let you deal with it very well.
Link Library header file:
Head. h

Class A {public: A (); virtual ~ A (); int gt (); int pt (); private: int s ;}; // He asked hovertree.com

Firstso. cpp

# Include <iostream> # include "head. h" A: A () {} ::~ A () {} int A: gt () {s = 10;} int A: pt () {std: cout <s <std :: endl;} // He asked hovertree.com

The compilation command is as follows:
G ++-shared-o libmy. so firstso. cpp
At this time, generate the libmy. so file and copy it to the System Library:/Usr/lib/
Perform secondary encapsulation:

Secso. cpp

# Include <iostream> # include "head. h "extern" C "{int f (); int f () {A a;. gt (); a.pt (); return 0 ;}// he asked hovertree.com

Compile command:
Gcc-shared-o sec. so secso. cpp-L.-lmy
At this time, the second. so file is generated. At this time, the Library is changed from a class to a c interface.
Copy/Usr/lib
Call the following:
Test. c

# Include "stdio. h "# include" dlfcn. h "# define SOFILE" sec. so "int (* f) (); int main () {void * dp; dp = dlopen (SOFILE, RTLD_LAZY); f = dlsym (dp," f "); f (); return 0;} // He asked hovertree.com

The compilation command is as follows:
Gcc-rdynamic-s-o myapp test. c

 

Run Z $./myapp

10
$

 

Http://www.cnblogs.com/roucheng/p/3456005.html

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.