[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
class A{
public:
A(){std::cout<<"A()"< virtual int print(){std::cout<<"A"< virtual ~A(){std::cout<<"~A()"<};
class B:public A {
public:
B(){std::cout<<"B()"< int print(){std::cout<<"B"< ~B(){std::cout<<"~B()"<};
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
#include
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<fun=reinterpret_cast(dlsym(dp, argv[2]));
if((error = dlerror()) != NULL) {
std::cerr<<"ERR:"<}
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]#
阅读(68593) | 评论(3) | 转发(1) |