python调C++的方式——2.

头文件

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这篇笔记记录用C++编写Python扩展模块的方式,以及与C语言编写Python模块的几个需要注意的不同点。

cppExample.cpp

// 简单的hello world 
#include "cppExample.h"

void CppEasyTest::helloWorld(){
    std::cout << "hello world" << std::endl;
    return;
}

cppExample.h

#include <iostream>
#include <stdio.h>

class CppEasyTest{
    public:
        CppEasyTest(){};
        ~CppEasyTest(){};
        void helloWorld();
};

cppExample_wrap.cpp

#include <Python.h>
#include "cppExample.h"           // @ 1 必须要包含声明C++类和方法的头文件


PyObject* wrap_helloWorld(PyObject* self, PyObject* args)      // @ 模块方法
{
    CppEasyTest* pobj = new CppEasyTest();
    pobj->helloWorld();
    delete pobj;
    pobj = NULL;
    return Py_BuildValue("");
}

static PyMethodDef cppExampleMethods[] =        // @ 模块列表
{
    {"helloWorld", wrap_helloWorld, METH_VARARGS, "print hello world"},
    {NULL, NULL}
};

extern "C"{                 // @ 2初始化时,必须要用extern "C" 否则g++编译器编译不过
void initcppExample(void)
{
    PyObject* m;
    m = Py_InitModule("cppExample", cppExampleMethods);
}
}

编译

g++ -fPIC -c -I /usr/include/python2.7/ -I /usr/lib/python2.7/config-x86_64-linux-gnu/ cppExample.cpp cppExample_wrap.cpp
g++ -shared -o cppExample.so cppExample.o cppExample_wrap.o

python测试

import cppExample
if __name__ == "__main__":
  ## @ 2 C++编写的python模块
  print cppExample.helloWorld()
  '''
hello world
None
'''

和 C语言编写Python扩展模块不同的是:
1.在wrap文件中必须要include包含C++方法的头文件不然会报错;
2.初始化方法要extern “C”
3.编译使用g++(废话)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值