Linux下python如何调用c++的代码,用ctypes方法。。

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文件,这个文件就是静态链接库了

# -*- coding:utf-8 -*-
from ctypes import *


def go_c(strs, ints):
    # 加载动态链接库或静态链接库
    dll = cdll.LoadLibrary("/home/baobao/CLionProjects/my_chasses/hello.so")
    # 这里是要传入的参数,要将str转换为bytes类型
    strs = bytes(strs, 'utf-8')

    # 这里调用返回int函数的c语言函数
    r_int = dll.get_int(strs, ints)
    print("返回的int是:", r_int, " 类型是:", type(r_int))

    # 这里调用返回string函数的C语言函数
    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'>
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值