python 调用 C++ code

本文通过实例代码详细介绍了如何使用Python调用C++的方法,包括无参数传递和有参数传递的情况。首先解释了将函数声明为C可用函数以被Python调用的基本原理,并提供了具体示例。接着,利用SWIG工具简化了调用过程,通过生成中间文件并编译动态链接库实现了C++函数在Python环境中的无缝调用。最后,展示了整个程序结构,包括Python调用C++函数的步骤和最终结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文以实例code讲解python 调用 C++的方法。
1. 如果没有参数传递从python传递至C++,python调用C++的最简单方法是将函数声明为C可用函数,然后作为C code被python调用,如这里三楼所示;
2. 有参数传递至C++函数,swig是最便捷的调用方法,以下面这个工程所示为例;


rachel.i (swig文件):

%module rachel
%{
#include "rachel.h"
%}

extern int linear(int x, int w, int b);

C++ code 部分:

rachel.h:

#include<stdio.h>                 
#include<Python.h>                

int linear(int x, int w, int b);  

rachel.cpp:

#include "rachel.h"       

int linear(int x, int w, int b){ 
    int res = w * x + b;         
    printf("%d\n", res);         
    return res;                  
}                                

执行命令:

swig -c++ -python rachel.i
g++ -c -fPIC rachel_wrap.cxx -I/home/zhangruiqing01/.jumbo/include/python2.7 -I./include
g++ -shared rachel.o rachel_wrap.o -o _rachel.so

第一句swig生成rachel_warp.cxx (如果是C,则用swig -python rachel.i生成rachel_warp.c文件);
最后一句生成动态链接库_rachel.so供python调用(如果是C,则用ld -shared rachel.o rachel_warp.o -o _rachel.so);

python 调用部分:

>>> import _rachel
>>> _rachel.linear(1,2,5)
7

最后看一下本文中程序的结构:


这里写图片描述

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值