First, take a look at the test procedures
1. Library section
Hello.h
#ifndef android_hello_h
#define ANDROID_HELLO_H
class hello_base
{public
:
virtual ~hello_base () {};
virtual int setctl (int ctl) = 0;
virtual int getctl (int ctl) = 0;
};
Class Hello:public Virtual hello_base
{public
:
virtual ~hello () {};
Static hello* Instance ();
int setctl (int ctl);
int getctl (int ctl);
Private:
static hello* _instance;
int myctl;
};
extern "C" hello_base* Creathello ();
typedef hello_base* Creathelloclass ();
#endif
Hello.cpp
#include "hello.h"
#include <stdio.h>
extern "C" hello_base* Creathello () {return
hello::instance ( );
}
hello* hello::_instance = 0;
hello* hello::instance ()
{
printf ("TK------>>>>>>hello::instance---------\ n");
if (_instance = = 0) {
_instance = new Hello ();
}
return _instance;
}
int hello::setctl (int ctl)
{
printf ("TK------->>>>>>setctl-----\ n");
This->myctl = CTL;
return 1;
}
int hello::getctl (int ctl)
{
printf ("TK------->>>>>>getctl-----\ n");
Return this->myctl;
}
Compiled into a dynamic link library, general requirements for PIC location are irrelevant:
g++-shared-fpic-o libhello.so Hello.cpp
Build: libhello.so
2. Test Cases
Test.cpp
#include "so/hello.h"
#include <stdio.h>
#include <dlfcn.h>
int main ()
{
void* Hello = Dlopen ("/home/lianxi/c++/ku/so/libhello.so", rtld_lazy);
if (!hello) {
printf ("dlopen/home/lianxi/c++/ku/so/libhello.so error!\n");
return-1;
}
Dlerror ();
creathelloclass* Creat_hello = (creathelloclass*) dlsym (Hello, "Creathello");
Const char* Dlsym_error = Dlerror ();
if (dlsym_error) {
printf ("Error%s\n", dlsym_error);
return-1;
}
hello_base* Mhello = Creat_hello ();
Mhello->setctl (5);
int result = MHELLO->GETCTL (0);
printf ("TK------>>>>>result is%d\n", result);
Dlclose (hello);
return 1;
}
Compiling: g++-o test test.cpp-l.-ldl
Execution./test results:
TK------>>>>>>hello::instance---------
tk------->>>>>>setctl-----
TK------->>>>>>getctl-----
tk------>>>>>result is 5
Second, analysis
1.LIBDL Library for C language development, when you need to dlsym a symbol in C + +, you need to declare that the symbol in the library is extern "C", such as the example of extern "C" hello_base* Creathello ();
2. Because it's not possible to dlsym as many methods in C + + classes This use of C + + for pure virtual class instantiation is a run-time link characteristics, that is, in C + + for the class to use the dynamic link of the shared library, must define a pure virtual subclass.
For information about shared libraries in C, see the following links:
"C Compiler principle" dynamic loading and static loading of shared libraries