• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-09) 26次浏览 已收录 0个评论

准备工作:

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

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

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

notepad++:https:/本文来源gao*daima.com搞@代#码&网6/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;
}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:胶水语言Python与C/C++的相互调用的实现

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址