胶水语言Python与C/C++的相互调用

准备工作:

python:https://www.python.org/downloads/

Dev-C++:https://sourceforge.net/projects/orwelldevcpp/

gcc和g++:http://mingw-w64.org/doku.php

notepad++:https://notepad-plus.en.softonic.com/

 

一、Python调用C

步骤1:Csayhello.c

#include<stdio.h>

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 <python.h>
#include<iostream>

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

运行结果:

 

 

  • 12
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值