Linux下python如何调用c++的代码,用ctypes方法。。
ctypes方法是将c (c++)代码编译成动态链接库,python调用这个动态链接库调用c++的方法。下面例子调用了c++里面的类,这个类可以接收int和string的字符,并返回一个string给python,在c++代码中要添加extern “C”代码,用C的方式进行编译,否则无法调用,编译之后在python中找不到写的函数。
C++代码如下(main.cpp):
#include <iostream>
using namespace std;
class People{
public:
char* get_str(char*, int);
int get_int(char*, int);
private:
int x;
string y;
};
string Y="";
char* People::get_str(char *_y, int _x) {
this->x = _x;
this->y = _y;
cout<<"c 函数中 x is:"<<this->x<<endl;
cout<<"c 函数中 y is:"<<this->y<<endl;
Y = this->y;
return &(Y[0]);
}
int People::get_int(char * _y, int _x) {
this->x = _x;
this->y = _y;
return this->x;
}
extern "C"{
People p;
char* get_str(char* _y, int _x){
return p.get_str(_y, _x);
}
int get_int(char* _y, int _x){
return p.get_int(_y, _x);
}
}
编译为静态链接库(这里如果编译为动态链接库,在版本较低的服务器上运行,可能会有问题,所以选择编译为静态链接库)的方法如下:
g++ -o hello.so -shared -static-libstdc++ -fPIC main.cpp
之后会产生一个.so文件,这个文件就是静态链接库了
from ctypes import *
def go_c(strs, ints):
dll = cdll.LoadLibrary("/home/baobao/CLionProjects/my_chasses/hello.so")
strs = bytes(strs, 'utf-8')
r_int = dll.get_int(strs, ints)
print("返回的int是:", r_int, " 类型是:", type(r_int))
d_str = dll.get_str
d_str.restype = c_char_p
r_str = d_str(strs, ints)
r_str = str(r_str)
print("返回的string 是:", r_str, " 类型为:", type(r_str))
go_c("hello", 111)
在python中输出的结果:
返回的int是: 111 类型是: <class 'int'>
c 函数中 x is:111
c 函数中 y is:hello
返回的string 是: b'hello' 类型为: <class 'str'>