- 论坛徽章:
- 0
|
用c去调用c++的函数库,是我一直想做的事情.今天晚上有了头绪.
main.c
#include
#include
int main()
{
printf("C++ dlopen demo
");
printf("Opening hello.so...
");
void* handle = dlopen("./hello.dll", RTLD_LAZY);
if (!handle) {
fprintf(stderr, "Cannot open library: %d
" , dlerror());
return 1;
}
printf("Loading symbol hello...
");
typedef void (*hello_t)();
hello_t hello = (hello_t) dlsym(handle, "hello");
if (!hello) {
fprintf(stderr, "Cannot load symbol 'hello': %d
" ,dlerror());
dlclose(handle);
return 1;
}
// use it to do the calculation
printf("Calling hello...
");
hello();
// close the library
printf("Closing library...
");
dlclose(handle);
}
以上程序是用c写的,它的功能很简单,就是用dlopen打开一个动态库,调用其中的一个函数.
如果这个动态库用c来写,则一点也不希奇.除非用c++来写,才有一点点看头.
hello.cpp
#include
#include
using namespace std;
class db
{
private:
string a;
public:
db()
{
a="abc";
}
~db()
{
a="";
}
void showme()
{
cout
这个就是用c++写的动态库.技巧就是声明一个全局函数,通过这个全局函数去调用类.当然,这个声明的时候要用 extern "C"来限定一下,这样在编译的时候,名字不会发生改变.
编译命令如下:
g++ -shared hello.cpp -o hello.dll
gcc main.cpp -o main.exe
这个程序是在cygwin下面调试的.
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/4353/showart_53463.html |
|