转自:http://www.cnblogs.com/tevic/p/3645197.html

最近在做一个CUDA的项目,记录下学习心得.

系统

Linux 3.11.0-19-generic #33-Ubuntu x86_64 GNU/Linux

C++调用Python

Python模块代码:

#!/usr/bin/python
#Filename:TestModule.py
def Hello(s):
print ("Hello World")
print(s) def Add(a, b):
print('a=', a)
print ('b=', b)
return a + b class Test:
def __init__(self):
print("Init")
def SayHello(self, name):
print ("Hello,", name)
return name

C++代码

#include<iostream>
#include<Python.h>
using namespace std;
int main(int argc, char* argv[])
{
//初始化python
Py_Initialize(); //直接运行python代码
PyRun_SimpleString("print('----------Python Start')"); //引入当前路径,否则下面模块不能正常导入
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')"); //引入模块
PyRun_SimpleString("print('----------PyImport_ImportModule')");
PyObject *pModule = PyImport_ImportModule("TestModule");
//获取模块字典属性
PyRun_SimpleString("print('----------PyModule_GetDict')");
PyObject *pDict = PyModule_GetDict(pModule); //直接获取模块中的函数
PyRun_SimpleString("print('----------PyObject_GetAttrString')");
PyObject *pFunc = PyObject_GetAttrString(pModule, "Hello"); //参数类型转换,传递一个字符串。将c/c++类型的字符串转换为python类型,元组中的python类型查看python文档
PyRun_SimpleString("print('----------Py_BuildValue')");
PyObject *pArg = Py_BuildValue("(s)", "Hello Charity"); PyRun_SimpleString("print('----------PyEval_CallObject')");
//调用直接获得的函数,并传递参数
PyEval_CallObject(pFunc, pArg); //从字典属性中获取函数
PyRun_SimpleString("print('----------PyDict_GetItemString Add function')");
pFunc = PyDict_GetItemString(pDict, "Add");
//参数类型转换,传递两个整型参数
pArg = Py_BuildValue("(i, i)", , ); //调用函数,并得到python类型的返回值
PyObject *result = PyEval_CallObject(pFunc, pArg);
//c用来保存c/c++类型的返回值
int c;
//将python类型的返回值转换为c/c++类型
PyArg_Parse(result, "i", &c);
//输出返回值
printf("a+b=%d\n", c); //通过字典属性获取模块中的类
PyRun_SimpleString("print('----------PyDict_GetItemString test class')");
PyObject *pClass = PyDict_GetItemString(pDict, "Test"); //实例化获取的类
PyRun_SimpleString("print('----------PyInstanceMethod_New test class')");
PyObject *pInstance = PyInstanceMethod_New(pClass);
//调用类的方法
PyRun_SimpleString("print('----------PyObject_CallMethod SayHello')");
result = PyObject_CallMethod(pInstance, "SayHello", "(Os)", pInstance, "Charity");
//输出返回值
char* name=NULL;
PyRun_SimpleString("print('----------PyArg_Parse')");
PyArg_Parse(result, "s", &name);
printf("%s\n", name); PyRun_SimpleString("print('Python End')"); //释放python
Py_Finalize();
getchar();
return ;
}

编译:

g++ -I/usr/include/python3.5 pythonwithcpp.cpp -L/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu -lpython3.5

运行结果:

root@ubuntu:/work/src/cython/cppcallpy# ./a.out
----------Python Start
----------PyImport_ImportModule
----------PyModule_GetDict
----------PyObject_GetAttrString
----------Py_BuildValue
----------PyEval_CallObject
Hello World
Hello Charity
----------PyDict_GetItemString Add function
a= 1
b= 2
a+b=3
----------PyDict_GetItemString test class
----------PyInstanceMethod_New test class
----------PyObject_CallMethod SayHello
Hello, Charity
----------PyArg_Parse
Charity
Python End

Python调用C++

C++代码:

1 //用C++必须在函数前加extern "C"
2 extern "C" int Add(int a,int b)
3 {
4 return a+b;
5 }

编译:

1 g++ -c -fPIC LibPythonTest.cpp
2 g++ -shared LibPythonTest.o -o LibPythonTest.so

Python代码:

1 #!/bin/python
2 #Filename:PythonCallCpp.py
3 from ctypes import *
4 import os
5 libPythonTest = cdll.LoadLibrary('./LibPythonTest.so')
6 print libPythonTest.Add(1,1)

运行:

1 python PythonCallCpp.py

运行结果:

2

[转]Linux下Python与C++混合编程的更多相关文章

  1. Linux下Python与C++混合编程

    最近在做一个CUDA的项目,记录下学习心得. 系统 Linux --generic #-Ubuntu x86_64 GNU/Linux C++调用Python Python模块代码: #!/usr/b ...

  2. 在linux环境下python与C++混合编程

    参考:在linux环境下编译C++ 程序 linux下python3调用c代码或者python3调用c++代码 https://blog.csdn.net/u013179327/article/det ...

  3. Linux下Python 文件内容替换脚本

    Linux下Python 文件替换脚本 import sys,os if len(sys.argv)<=4: old_text,new_text = sys.argv[1],sys.argv[2 ...

  4. Linux下python安装升级详细步骤 | Python2 升级 Python3

    Linux下python升级步骤  Python2 ->Python3 多数情况下,系统自动的Python版本是2.x 或者yum直接安装的也是2.x 但是,现在多数情况下建议使用3.x 那么如 ...

  5. linux下C语言socket网络编程简例

    原创文章,转载请注明转载字样和出处,谢谢! 这里给出在linux下的简单socket网络编程的实例,使用tcp协议进行通信,服务端进行监听,在收到client的连接后,发送数据给client:clie ...

  6. Linux下python安装升级详细步骤 | Python2 升级 Python3 转载

    Linux下python升级步骤  Python2 ->Python3 多数情况下,系统自动的Python版本是2.x 或者yum直接安装的也是2.x 但是,现在多数情况下建议使用3.x 那么如 ...

  7. linux下Python网络编程框架-Twisted安装

    Twisted是python下的用来进行网络服务和应用程序编程的框架,安装Twisted前需要系统预先安装有python. 一.安装Twisted http://twistedmatrix.com/R ...

  8. linux下python启动第三方程序,并控制关闭

    import subprocess import os import signal p = subprocess.Popen("recordmydesktop -o /home/test/t ...

  9. Linux下python升级步骤

    先安装openssl,openssl-devel yum install openssl yum install openssl-devel 1切换到指定的目录下: cd /usr/local 2下载 ...

随机推荐

  1. vue query或params传参

    1.query 传递端: this.$router.push({ path:"/AccountFP", query:{ id:row.id, userId:row.userId } ...

  2. VXLAN, 一种叠加在L3网络上的L2网络

    这几天看了下RFC7348,顺便翻译了一下,根据自己理解做了注解 虚拟化及租户隔离 服务器虚拟化增加了对物理网络基础设施的需求,服务器有多个虚机,要求交换机支持更大的MAC地址表. 在数据中心场景下, ...

  3. ranch流程处理图

    ranch是开发服务端管理模板,这个模板不大,写的很经典,方便并发管理,而且性能很优秀~~ 其中比较优秀的就有cowboy~~ 看了一下ranch的源码(版本v1.2.1 下载链接https://gi ...

  4. 『Python CoolBook』Cython_高效数组操作

    数组运算加速是至关科学计算重要的领域,本节我们以一个简单函数为例,使用C语言为python数组加速. 一.Cython 本函数为一维数组修剪最大最小值 version1 @cython.boundsc ...

  5. html5(一)

    HTML5 三个基本特色:结构.样式.功能. <!DOCTYPE html ><html lang="en"><head> <meta c ...

  6. 关于c#连接数据库的代码

    using System;using System.Collections.Generic;using System.Data;using System.Data.SQLite;using Syste ...

  7. python--jianja2

    一:渲染模版 要渲染一个模板,通过render_template方法即可. @app.route('/about/')def about():return render_template('about ...

  8. C++ File Binary

    论操作非文本文件时,std::ios::binary的重要性 今天在读取图片文件的时候,根据图片数据的高宽对图片数据进行读取,但是出现了图片数据读取不完整,但是文件已经到达末尾的情况,中间想过read ...

  9. 剖析 GSM 加密机制以及位置更新的过程

    你有没有想过打开手机时会发生什么?它是如何以安全的方式与网络进行通信?几乎所有人都知道TCP / IP,并且可能许多人还是专家,但是谈到电信方面,很少有人知道它的内部原理. gsm中的消息结构是什么? ...

  10. Java学习笔记42(数据库连接池 druid连接池)

    druid连接池: 是阿里的连接池,druid的稳定性及效率都很高,目前用的比较广,所以建议开发过程中尽量用druid连接池(支持国产最重要) druid连接池也需要配置文件,配置文件必须是prope ...