python脚本利用ctypes调用c模块返回字符串

时间:2021-05-03 16:13:06
  • 如何利用python来调用c的静态链接库呢?
  • 如何利用python获取c库返回的字符串呢?

这里贴出几段简单的代码,希望能够帮助大家(有更好的欢迎交流哦)

/// test.h ///
#include <iostream>
using namespace std;
bool get_func_name(string &data);
/// test.cpp ///
#include "test.h"
bool get_func_name(string &data){
data = "get_func_name";
return true;
}
/// 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());
}
}
/// 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
## test.py
import ctypes
obj = ctypes.CDLL("./libtest.so")
rst = obj.get_func_name_wrap()

data = ctypes.string_at(rst, -1).decode("utf-8")
print data
$python test.py
get_func_name

注意事项:

  • 静态编译的时候别忘记加-fpic