c++“反射”?

[root@FC5 cppclass]# cat Makefile
TARGET = mytest
all:$(TARGET)
$(TARGET):test.cpp libcpp.so
        g++ -g -o $@ test.cpp -L. -lcpp -ldl
libcpp.so:cppclass.cpp
        g++ -shared -o $@  cppclass.cpp -fPIC
        cp -r libcpp.so /lib
clean:
        rm -r $(TARGET) libcpp.so
[root@FC5 cppclass]# cat cppclass.cpp
#include <iostream>
class A{
public:
        A(){std::cout<<"A()"<<std::endl;}
        virtual int print(){std::cout<<"A"<<std::endl;}
        virtual ~A(){std::cout<<"~A()"<<std::endl;};
};
class B:public A {
public:
        B(){std::cout<<"B()"<<std::endl;}
        int print(){std::cout<<"B"<<std::endl;}
        ~B(){std::cout<<"~B()"<<std::endl;}
};
extern "C" {
A* fun_A()
{
A x;
return &x;
};
B* fun_B()
{
B x;
return &x;
}
}
[root@FC5 cppclass]# cat test.cpp
/*test.c*/
#include <iostream>
#include <dlfcn.h>
class A{
public:
 A();
 int print();
 ~A();
};
//A* fun_A();
A* (*fun)();
int main(int argc,char ** argv)
{
void *dp;
char *error;
dp=dlopen(argv[1], RTLD_LAZY);
if(!dp){
        fprintf(stderr, "%s/n", dlerror());
        return -1;
}
dlerror();
std::cout<<argv[2]<<std::endl;
fun=reinterpret_cast<A* (*)() >(dlsym(dp, argv[2]));
if((error = dlerror()) != NULL) {
        std::cerr<<"ERR:"<<error<<std::endl;
}
fun()->print();
dlclose(dp);
return 0;
}
[root@FC5 cppclass]#
[root@FC5 cppclass]# make
g++ -shared -o libcpp.so  cppclass.cpp -fPIC
cppclass.cpp: In function 'A* fun_A()':
cppclass.cpp:17: warning: address of local variable 'x' returned
cppclass.cpp: In function 'B* fun_B()':
cppclass.cpp:22: warning: address of local variable 'x' returned
cp -r libcpp.so /lib
g++ -g -o mytest test.cpp -L. -lcpp -ldl
[root@FC5 cppclass]# ./mytest libcpp.so fun_A
fun_A
A()
~A()
A
[root@FC5 cppclass]# ./mytest libcpp.so fun_B
fun_B
A()
B()
~B()
~A()
A
[root@FC5 cppclass]#
 

你可能感兴趣的:(C++,function,Class,iostream,makefile,fun)