
胶水语言Python与C/C++的相互调用
发布日期:2021-05-07 10:36:05
浏览次数:21
分类:精选文章
本文共 2194 字,大约阅读时间需要 7 分钟。
准备工作:
python:
Dev-C++:
gcc和g++:
notepad++:
一、Python调用C
步骤1:Csayhello.c
#includevoid show_hello(){ printf("------------来自C语言的问候-----------\n"); printf("-----Peter Zhao says:Hello C world!-----\n\n");}
步骤2:
命令:gcc Csayhello.c -fPIC -shared -o lib_Csayhello.so
步骤3:Psayhello.py
from ctypes import *#加载动态库lib = cdll.LoadLibrary(r"./lib_Csayhello.so")lib.show_hello()print("-----------来自Python语言的问候--------------")print("---Peter Zhao says:Hello Python world,too!---")
步骤4:
命令:python Psayhello.py
注意:python为32位,没有就装一个。
运行结果:
二、Python调用C++
步骤1:新建项目dll_demo.dev
步骤2:dllmain.cpp
#define DLLEXPORT extern "C" __declspec(dllexport)DLLEXPORT int multiply(int a, int b) { return a * b;}//两数相加DLLEXPORT int add(int a, int b) { return a + b;}//两数相减DLLEXPORT int sub(int a, int b) { return a-b;}
步骤3:dll.h
int multiply(int, int);class Mymath { int sum(int, int); int sub(int, int);};
步骤4:编译生成dll_demo.dll
步骤5:Pdll_demo.py
import ctypes#lib = ctypes.cdll.LoadLibrary(r"./dll_demo.dll")lib = ctypes.WinDLL(r"./dll_demo.dll")#print(lib)print(lib.multiply(80,95))print(lib.add(80,95))print(lib.sub(80,95))
步骤6:
命令:python Pdll_demo.py
注意:python为32位,没有就装一个。
运行结果:
三、C++调用Python函数
步骤1:Caculate.py
def add(a,b): return a+b
步骤2:新建项目test.dev,然后设置一下“项目属性”的链接库、库目录、包含文件目录等3个部分。
步骤3:test.cpp
#include#include using namespace std;int main(){ Py_Initialize();//使用python之前,要调用Py_Initialize();这个函数进行初始化 if (!Py_IsInitialized()) { printf("初始化失败!"); return 0; } PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')");//这一步很重要,修改Python路径 PyObject * pModule = NULL;//声明变量 PyObject * pFunc = NULL;// 声明变量 pModule = PyImport_ImportModule("Caculate");//这里是要调用的文件名Caculate.py if (pModule==NULL) { cout << "没找到" << endl; } pFunc = PyObject_GetAttrString(pModule, "add");//这里是要调用的函数名 PyObject* args = Py_BuildValue("(ii)", 100, 120);//给python函数参数赋值 PyObject* pRet = PyObject_CallObject(pFunc, args);//调用函数 int res = 0; PyArg_Parse(pRet,"i",&res);//转换返回类型 cout << "res:" << res << endl;//输出结果 Py_Finalize();//调用Py_Finalize,这个根Py_Initialize相对应的。 return 0;}
步骤4:编译并运行
运行结果:
发表评论
最新留言
留言是一种美德,欢迎回访!
[***.207.175.100]2025年03月21日 20时50分48秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
MVC学习系列5--Layout布局页和RenderSection的使用
2019-03-06
MVC学习系列13--验证系列之Remote Validation
2019-03-06
多线程之volatile关键字
2019-03-06
2.1.4奇偶校验码
2019-03-06
2.2.2原码补码移码的作用
2019-03-06
多线程之Lock显示锁
2019-03-06
ForkJoinPool线程池
2019-03-06
【Struts】配置Struts所需类库详细解析
2019-03-06
Java面试题:Servlet是线程安全的吗?
2019-03-06
DUBBO高级配置:多注册中心配置
2019-03-06
Java集合总结系列2:Collection接口
2019-03-06
Linux学习总结(九)—— CentOS常用软件安装:中文输入法、Chrome
2019-03-06
大白话说Java反射:入门、使用、原理
2019-03-06
集合系列 Set(八):TreeSet
2019-03-06
JVM基础系列第11讲:JVM参数之堆栈空间配置
2019-03-06
MySQL用户管理:添加用户、授权、删除用户
2019-03-06
比技术还重要的事
2019-03-06
linux线程调度策略
2019-03-06
软中断和实时性
2019-03-06
Linux探测工具BCC(可观测性)
2019-03-06