Python调用C++


1.C++开发使用Python,首先需要在Python中安装依赖包,对于centos可以使用yum search python-dev,之后采用yum install 安装。

2.安装python,用源码安装,经过./configure,make,make install后生成libpython2.7.a。

3.可能会需要一些其他的库,eg:   gcc Test.cpp -I /usr/include/python2.7/ -L/usr/local/lib/ -lpython2.7 -pthread -ldl -lm -lutil

4.C++代码可以如下:

#include<Python.h>//前面所做的一切配置都是为了调用这个头文件和相关库
int main()
{
    Py_Initialize();//使用python之前,要调用Py_Initialize();这个函数进行初始化
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");
    PyObject * pModule = NULL;//声明变量
    PyObject * pFunc = NULL;// 声明变量
    pModule =PyImport_ImportModule("helloworld");//这里是要调用的文件名
    pFunc= PyObject_GetAttrString(pModule, "hello");//这里是要调用的函数名
    PyEval_CallObject(pFunc, NULL);//调用函数
    Py_Finalize();//调用Py_Finalize,这个根Py_Initialize相对应的。
    return 0;
}


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

C++调用Python

Python模块代码:

 1 #!/usr/bin/python
 2 #Filename:TestModule.py
 3 def Hello(s):
 4     print "Hello World"
 5     print s
 6 
 7 def Add(a, b):
 8     print 'a=', a
 9     print 'b=', b
10     return a + b
11 
12 class Test:
13     def __init__(self):
14         print "Init"
15     def SayHello(self, name):
16         print "Hello,", name
17         return name

C++代码:

 1 #include<iostream>
 2 #include<Python.h>
 3 using namespace std;
 4 int main(int argc, char* argv[])
 5 {
 6     //初始化python
 7     Py_Initialize();
 8 
 9     //直接运行python代码
10     PyRun_SimpleString("print 'Python Start'");
11 
12     //引入当前路径,否则下面模块不能正常导入
13     PyRun_SimpleString("import sys");  
14     PyRun_SimpleString("sys.path.append('./')");  
15 
16     //引入模块
17     PyObject *pModule = PyImport_ImportModule("TestModule");
18     //获取模块字典属性
19     PyObject *pDict = PyModule_GetDict(pModule);
20 
21     //直接获取模块中的函数
22     PyObject *pFunc = PyObject_GetAttrString(pModule, "Hello");
23 
24     //参数类型转换,传递一个字符串。将c/c++类型的字符串转换为python类型,元组中的python类型查看python文档
25     PyObject *pArg = Py_BuildValue("(s)", "Hello Charity");
26 
27     //调用直接获得的函数,并传递参数
28     PyEval_CallObject(pFunc, pArg);
29 
30     //从字典属性中获取函数
31     pFunc = PyDict_GetItemString(pDict, "Add");
32     //参数类型转换,传递两个整型参数
33     pArg = Py_BuildValue("(i, i)", 1, 2);
34 
35     //调用函数,并得到python类型的返回值
36     PyObject *result = PyEval_CallObject(pFunc, pArg);
37     //c用来保存c/c++类型的返回值
38     int c;
39     //将python类型的返回值转换为c/c++类型
40     PyArg_Parse(result, "i", &c);
41     //输出返回值
42     printf("a+b=%d\n", c);
43 
44     //通过字典属性获取模块中的类
45     PyObject *pClass = PyDict_GetItemString(pDict, "Test");
46 
47     //实例化获取的类
48     PyObject *pInstance = PyInstance_New(pClass, NULL, NULL);
49     //调用类的方法
50     result = PyObject_CallMethod(pInstance, "SayHello", "(s)", "Charity");
51     //输出返回值
52     char* name=NULL;
53     PyArg_Parse(result, "s", &name);
54     printf("%s\n", name);
55 
56     PyRun_SimpleString("print 'Python End'");
57 
58     //释放python
59     Py_Finalize();
60     getchar();
61     return 0;
62 }

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)



Python调用C++代码可以通过多种方法实现,主要包括使用扩展模块、C/C++接口封装以及工具链辅助生成绑定代码等方式。以下是几种常见且实用的方案: ### 1. 使用 `ctypes` 调用 C 风格共享库 虽然 `ctypes` 主要用于调用 C 编写的动态链接库(如 `.so` 或 `.dll`),但可以通过将 C++ 代码编译为具有 `extern "C"` 导出符号的共享库来间接调用 C++ 函数。 ```cpp // hello.cpp #include <iostream> extern "C" { void greet() { std::cout << "Hello from C++!" << std::endl; } } ``` 编译为共享库: ```bash g++ -shared -fPIC -o libhello.so hello.cpp ``` 然后在 Python调用: ```python import ctypes lib = ctypes.CDLL('./libhello.so') lib.greet() ``` ### 2. 使用 `Boost.Python` 创建 Python 扩展 `Boost.Python` 是一个功能强大的库,允许你直接将 C++ 类和函数暴露给 Python。它需要安装 Boost 库并进行适当的配置。 ```cpp // example.cpp #include <boost/python.hpp> char const* greet() { return "Hello from C++ with Boost.Python!"; } BOOST_PYTHON_MODULE(example) { using namespace boost::python; def("greet", greet); } ``` 编译命令示例: ```bash g++ -I/usr/include/python3.8 -I/usr/local/include/boost -fPIC -shared example.cpp -o example.so -lboost_python38 -lpython3.8 ``` 然后在 Python 中导入并使用: ```python import example print(example.greet()) ``` ### 3. 使用 `pybind11` 构建轻量级绑定 `pybind11` 是一个现代、轻量级的头文件库,专为简化 C++Python 的交互而设计,推荐用于新项目。 ```cpp // main.cpp #include <pybind11/pybind11.h> int add(int i, int j) { return i + j; } PYBIND11_MODULE(example, m) { m.def("add", &add, "A function that adds two numbers"); } ``` 编译命令(确保已安装 pybind11): ```bash c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) main.cpp -o example$(python3-config --extension-suffix) ``` Python 中使用: ```python import example print(example.add(3, 4)) # 输出 7 ``` ### 4. 使用 SWIG 自动生成绑定代码 SWIG 是一个自动包装器生成工具,支持多种语言,包括 PythonC++。适用于已有大型 C++ 项目希望快速暴露接口给 Python 的场景。 假设有一个 `example.i` 接口定义文件: ```swig %module example %{ #include "example.h" %} int add(int a, int b); ``` 对应的 `example.h` 和 `example.cpp` 实现了 `add` 函数。使用 SWIG 生成绑定代码后,再编译为 Python 模块即可调用。 --- ##
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值