CPP绑定到python端(1)

本文介绍了Python扩展模块的开发,通过C++编写并集成到Python中,展示了如何利用C++的高性能计算能力实现斐波那契数列计算和自定义函数`mm`。通过`setup.py`构建扩展模块,并使用CMakeLists.txt进行编译配置。内容涵盖了PyCFunction、PyArg_ParseTuple等关键接口的使用。

Python扩展模块简介
Python与C/C++交互的方案有多种,如Python C API,SWIG,SIP,ctypes,cpython,cffi,boost.python等。
Python只是一个语言规范,有很多具体实现,CPython是标准Python,由C编写,Python脚本被编译成CPython字节码,然后由虚拟机解释执行,垃圾回收使用引用计数,Python与C/C++混合编程本质是基于CPython解释器。其它的Python实现包括Jython、IronPython、PyPy、Pyston,Jython是Java编写的,使用JVM的垃圾回收,可以与Java混合编程,IronPython面向.NET平台。
Python扩展模块可以用Python编写,也可以用C/C++编译型的语言来写扩展。Python可扩展性具有为语言增加新功能、具有可定制性、代码可以实现复用等优点。

cModPyDem.cpp


#include <Python.h>

//a func to calc fib numbers
int cFib(int n)
{
    if (n<2) return n;
    return cFib(n-1) + cFib(n-2);
}


static PyObject* fib(PyObject* self,PyObject* args)
{
    int n;
    if (!PyArg_ParseTuple(args,"i",&n))
        return NULL;
    return Py_BuildValue("i",cFib(n));
}

static PyMethodDef module_methods[] = {
        {"fib",(PyCFunction) fib, METH_VARARGS,"calculates the fibonachi number"},
        {NULL,NULL,0,NULL}
};
static struct PyModuleDef cModPyDem =
        {
                PyModuleDef_HEAD_INIT,
                "cModPyDem", /* name of module */
                "",          /* module documentation, may be NULL */
                -1,          /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
                module_methods
        };


PyMODINIT_FUNC PyInit_cModPyDem(void)
{
    return PyModule_Create(&cModPyDem);
    //#需要注意的是Extension cModPyDem名字需和PyInit_ cModPyDem保持一致

}

cppdemo2


#include <Python.h>
#include <iostream>
using namespace std;
//a func to calc fib numbers
int cFib(int n)
{
    if (n<2) return n;
    return cFib(n-1) + cFib(n-2);
}
int cmm(int n,int m)
{
    std::cout<<"0nnnnnn"<<n<<std::endl;
    std::cout<<"0mmmm"<<m<<std::endl;

    return m*n;
}


static PyObject* mm(PyObject* self,PyObject* args)
{
    int n,m;
    std::cout<<"1nnnnnn"<<n<<std::endl;
    std::cout<<"1mmmm"<<m<<std::endl;
    if (!PyArg_ParseTuple(args,"ii",&n,&m))
        return NULL;
    int res=cmm( n, m);
    std::cout<<"resres"<<res<<std::endl;
    return Py_BuildValue("i",res);
}


static PyObject* fib(PyObject* self,PyObject* args)
{
    int n;
    if (!PyArg_ParseTuple(args,"i",&n))
        return NULL;
    return Py_BuildValue("i",cFib(n));
}

static PyMethodDef module_methods[] = {
        {"fib",(PyCFunction) fib, METH_VARARGS,"calculates the fibonachi number"},
        {"mmse",(PyCFunction) mm, METH_VARARGS,"calculates mm"},


        {NULL,NULL,0,NULL}
};
static struct PyModuleDef cModPyDem =
        {
                PyModuleDef_HEAD_INIT,
                "pttf._c", /* name of module */
                "",          /* module documentation, may be NULL */
                -1,          /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
                module_methods
        };


PyMODINIT_FUNC PyInit_cModPyDem(void)
{
    return PyModule_Create(&cModPyDem);
}

setup.py

from distutils.core import setup, Extension

module = Extension('cModPyDem', sources=['cModPyDem.cpp'])
#需要注意的是cModPyDem名字需和PyInit_ cModPyDem保持一致
setup(name = 'facebook1',
      version='10.0',
      description = 'a test package',
      ext_modules = [module])

test.py

import cModPyDem

if __name__ == '__main__' :

    print(cModPyDem.fib(200))

CmakeList

cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(pycppbind)


add_executable(pycppbind pyth.cpp)
set(Python_Libs "/home/XX/python3.7")
file(GLOB Python_Libs_a ${Python_Libs}/*.a)
file(GLOB Python_Libs_so ${Python_Libs}/*.so)

include_directories("/home/XX/include/python3.7m")

target_link_libraries(pycppbind ${Python_Libs_a} ${Python_Libs_so}

        )

set_property(TARGET pycppbind PROPERTY CXX_STANDARD 14)

参考文章

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值