python调用C++方法

2022-12-08 08:29:55

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


python调用C++方法

前言

提示:这里可以添加本文要记录的大概内容:

python 通过ctypes包调用c++或者c 的方法


提示:以下是本篇文章正文内容,下面案例可供参考

一、C++代码

C++中通过 extern “C” { xxxx } 将需要python调用的方法 包含起来,然后打包编译即可,C则不需要使用extern直接就能调用,例如:

extern "C" {

ECG_Info cpeek5(int a, int b, int c, int d, int e, int* fdat)
    {
        ECG_Info ecgInfo;
        *fdat = 1000;
        printf("%d",*fdat);

        ecgInfo.a= 1;
        return ecgInfo;
    }
}

进行编译,例如:

#如果编译的环境配置不匹配,linux切换编译环境(提前安装更新好c++编译环境)
scl enable devtoolset-9 bash
#编译
gcc test.cpp  -fPIC -shared -o test.so -lstdc++

二、Python代码

1.引入库

代码如下(示例):

import ctypes
or
from ctypes import *
#传递结构体作为参数或者返回值
class Ecginfo(Structure):
    _fields_ = [
        ("a", c_int),
        ("b", c_int),
        ("c", c_int),
        ("d", c_short),
        ("e", c_char)
    ]

#加载so文件
productC = cdll.LoadLibrary('/home/hd/mlflow/data/github/c/EPLimited_fix_datatest/a_product.so')
cpeek5= productC.cpeek5
#设置方法参数类型
cpeek5.argtypes=[ctypes.c_int,ctypes.c_int,ctypes.c_int,ctypes.c_int,ctypes.c_int,ctypes.POINTER(ctypes.c_int)]
#设置方法返回值类型
cpeek4.restype=Ecginfo


#调用方法
fdat_p = ctypes.pointer(ctypes.c_int(0)) # 传递指针变量
product_peek = cpeek5(ctypes.c_int(dat[i]),ctypes.c_int(filted[i]),ctypes.c_int(884),ctypes.c_int(100),ctypes.c_int(60),fdat_p)
#打印修改后的指针变量的结果,值发生了改变
print("fdatum: "+str(fdat_p[0]))


总结

主要对python调用c++的方式介绍,并传递指针变量 , 常规变量 和 对象作为返回值的demo。
  • 作者:gg1314723
  • 原文链接:https://blog.csdn.net/gg1314723/article/details/127635956
    更新时间:2022-12-08 08:29:55