1.编写cpp文件
#include "pycpp.h"
#include <iostream>using namespace std;PyCpp::PyCpp(){}void PyCpp::sayHello(int a){cout << "Hello Python, I am C++."<<a << endl;
}
2.编写头文件(声明变量)
class PyCpp{
public:PyCpp();void sayHello(int a);
};
// 不能定义编译器生成的特殊成员函数(必须首先在类中声明)
3.编写.i文件,用于链接
%module pycpp%{
#include "pycpp.h"
%}%include "pycpp.h"
4.在同级目录下放python.h(去conda的env里面找)
5.下载swig运行代码
swig -c++ -python 1/pycpp.i
生成_wrap.cxx
6.编写setup.py
from distutils.core import setup, Extension
pycpp_module = Extension('_pycpp',sources=['pycpp.cpp', 'pycpp_wrap.cxx',],)
setup (name = 'pycpp',version = '0.1',author = "NZACH",description = """Simple swig C\+\+/Python example.""",ext_modules = [pycpp_module],py_modules = ["pycpp"],)
7.运行setup.py
python setup.py build_ext --inplace
8.使用
>>> import pycpp
>>> pycpp.PyCpp().sayHello(12)
Hello Python, I am C++.12