Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1086247
  • 博文数量: 80
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 746
  • 用 户 组: 普通用户
  • 注册时间: 2018-06-12 20:01
个人简介

寫写code、调調bug、填填坑,僅此而已。

文章分类

全部博文(80)

文章存档

2019年(30)

2018年(50)

分类: C/C++

2019-03-14 17:12:15

1.编写c++用例
test.h

点击(此处)折叠或打开

  1. #include<iostream>
  2. using namespace std;
  3. class MyClass
  4. {
  5. public:
  6.     MyClass();
  7.     ~MyClass();
  8.     unsigned char *test(int length);

  9. private:
  10.     int m_key;

  11. };
test.cpp

点击(此处)折叠或打开

  1. #include "test.h"

  2. MyClass::MyClass()
  3. {
  4.    m_key=56;
  5. }
  6. MyClass::~MyClass()
  7. {

  8. }
  9. unsigned char * MyClass::test(int length)
  10. {
  11.    cout<<"m_key=="<<m_key<<endl;
  12.    length=256;
  13.    unsigned char *p;
  14.    p=new unsigned char[3];
  15.    p[0]=1;
  16.    p[1]=2;
  17.    p[2]=3;
  18.    return p;
  19. }
2.编写用于c调用c++成员函数
callC.cpp

点击(此处)折叠或打开

  1. #include "test.h"
  2. MyClass myc;
  3. extern "C"
  4. {
  5.     unsigned char * callCtest(int length);
  6. }
  7. unsigned char * callCtest(int length)
  8. {
  9.     return myc.test(length);
  10. }
3.编译c++动态库
g++ test.cpp callC.cpp -o libtest.so
4.编写main.c 调用libtest.so
main.c

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<dlfcn.h>

  3. #define LIB_PATH "/root/test/-libtest.so"
  4. typedef unsigned char * (*CTest)(int length);
  5. int main()
  6. {
  7.     
  8.     void *handle;
  9.     CTest ctest=NULL;
  10.     handle=dlopen(LIB_PATH,RTLD_LAZY);
  11.     if(!handle)
  12.     {
  13.         fprintf(stderr, "%s\n",dlerror() );
  14.         return 1;
  15.     }
  16.     
  17.     *(void **) (&ctest)=dlsym(handle,"callCtest");
  18.     int len;
  19.     unsigned char *t;
  20.     t=ctest(len);
  21.     printf("len===%d\n",len);
  22.     printf("p[1]=%d\n",t[1]);
  23.     dlclose(handle);
  24.     return 0;
  25. }
5.编译main.c
gcc main.c -o cmain -L. -ltest
6.运行cmain

  export LD_LIBRARY_PATH=/root/test

./cmain


阅读(87586) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~