• 主页
  • 树洞
  • 基础知识
  • 源码阅读
所有文章 关于我

  • 主页
  • 树洞
  • 基础知识
  • 源码阅读

python调用C++

2021-02-07
  • 利用python来调用c的静态链接库
  • 利用python获取c库返回的字符串
1
2
3
4
/// test.h ///
#include <iostream>
using namespace std;
bool get_func_name(string &data);
1
2
3
4
5
6
/// test.cpp ///
#include "test.h"
bool get_func_name(string &data){
data = "get_func_name";
return true;
}
1
2
3
4
5
6
7
8
9
10
11
/// test_wrap.cpp ///
#include "test.h"
#include "string.h"

extern "C" {
char * get_func_name_wrap(){
static string name;
get_func_name(name);
return const_cast<char*>(name.c_str());
}
}
1
2
3
4
/// compile sh
g++ -fpermissive -fpic -c test.cpp -o test.o
ar rcs libtest.a test.o
g++ -fpermissive -fpic -shared test_wrap.cpp -o libtest.so libtest.a