调用C++ .so文件

来源:互联网 发布:流浪儿童现状数据 编辑:程序博客网 时间:2024/06/05 13:29

目标:使用C++成功调用C++文件生成的.so文件

场景:最近在设计交易系统,有使用到C++中间件层调用后台服务的状态,现在简单熟悉下怎样用C++动态的去调用.so文件。

过程:

1. 一般的交易系统后台系统都有中间件层和后台业务逻辑层,写技术的玩玩中间件,写业务的专注于后台业务逻辑处理。今天我们看看怎么样去调用.so文件。

首先列出test.h文件

#ifndef _test_h_

#define _test_h_

 

#include<string.h>

#include<stdio.h>

#include<stdlib.h>

#include<string>

#include<iostream>

using namespacestd;

 

class Test

{

private:

  int a;

  int b;

 

public:

  int getResult( char* pXMLIn, char* pXMLOut);

};

 

#endif

 

#ifdef__cplusplus  //注意 这里是双下划线

extern"C"

{

#endif

int getCResult(char* pXMLIn, char* pXMLOut);

#ifdef__cplusplus

}

#endif

 

 

 

 

#include"test.h"

 

intTest::getResult(char* pXMLIn, char* pXMLOut)

{

 cout<<"pXMLIn ="<<pXMLIn<<endl;

 strcpy(pXMLOut,"<entrust_serial_no>1000</entrust_serial_no>");

 cout<<"pXMLOut ="<<pXMLOut<<endl;

}

 

int getCResult(char* pXMLIn, char* pXMLOut)

{

  cout<<"entr"<<endl;

  Test* pTest = new Test();

  pTest->getResult(pXMLIn,  pXMLOut);

  delete pTest;

  return 0;

}

 

 

最后main文件

#include<stdio.h>  

#include<dlfcn.h>

#include<stdlib.h>  

#include<iostream>  

using namespacestd;

 

int main()

{

  void* handle =dlopen("./libtest.so",RTLD_LAZY);

  if(handle == NULL)

  {

    cout<<"handleerror"<<endl;

    return 0;

   }

  typedef int(*server)( char*, char*);

  server s= (server)dlsym(handle,"getCResult");

  if(s == NULL)

  {

    cout<<"server error:"<<dlerror()<<endl;

    dlclose(handle);

    return 0;

  }

  char* sData = new char[1000];

  char ss[10] = "hello";

  cout<<"init"<<endl;

  (*s)(ss, sData);

  cout<<"sData ="<<sData<<endl;

  delete sData;

  dlclose(handle);

  return 0;

}

 

由以上可以看出,封装的.so文件真正达到了与主程序的隔离,其他的都可以通过配置参数进行获取,不管是.so文件还是主函数。

0 0
原创粉丝点击