胶水语言Python与C/C++的相互调用
发布日期:2021-05-07 10:36:05 浏览次数:21 分类:精选文章

本文共 2194 字,大约阅读时间需要 7 分钟。

准备工作:

python:

Dev-C++:

gcc和g++:

notepad++:

 

一、Python调用C

步骤1:Csayhello.c

#include
void 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:编译并运行

运行结果:

 

 

上一篇:Codeforces Global Round 14 A B C D E 题解
下一篇:Educational Codeforces Round 108 A B C D 题解

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2025年03月21日 20时50分48秒