1.编写c++用例
test.h
-
#include<iostream>
-
using namespace std;
-
class MyClass
-
{
-
public:
-
MyClass();
-
~MyClass();
-
unsigned char *test(int length);
-
-
private:
-
int m_key;
-
-
};
test.cpp
-
#include "test.h"
-
-
MyClass::MyClass()
-
{
-
m_key=56;
-
}
-
MyClass::~MyClass()
-
{
-
-
}
-
unsigned char * MyClass::test(int length)
-
{
-
cout<<"m_key=="<<m_key<<endl;
-
length=256;
-
unsigned char *p;
-
p=new unsigned char[3];
-
p[0]=1;
-
p[1]=2;
-
p[2]=3;
-
return p;
-
}
2.编写用于c调用c++成员函数
callC.cpp
-
#include "test.h"
-
MyClass myc;
-
extern "C"
-
{
-
unsigned char * callCtest(int length);
-
}
-
unsigned char * callCtest(int length)
-
{
-
return myc.test(length);
-
}
3.编译c++动态库
g++ test.cpp callC.cpp -o libtest.so
4.编写main.c 调用libtest.so
main.c
-
#include<stdio.h>
-
#include<dlfcn.h>
-
-
#define LIB_PATH "/root/test/-libtest.so"
-
typedef unsigned char * (*CTest)(int length);
-
int main()
-
{
-
-
void *handle;
-
CTest ctest=NULL;
-
handle=dlopen(LIB_PATH,RTLD_LAZY);
-
if(!handle)
-
{
-
fprintf(stderr, "%s\n",dlerror() );
-
return 1;
-
}
-
-
*(void **) (&ctest)=dlsym(handle,"callCtest");
-
int len;
-
unsigned char *t;
-
t=ctest(len);
-
printf("len===%d\n",len);
-
printf("p[1]=%d\n",t[1]);
-
dlclose(handle);
-
return 0;
-
}
5.编译main.c
gcc main.c -o cmain -L. -ltest
6.运行cmain
export LD_LIBRARY_PATH=/root/test
./cmain
阅读(87700) | 评论(0) | 转发(0) |