通过SWIG实现在Python中调用C++代码

发布于 3 天前  15 次阅读


Please refresh the page if equations are not rendered correctly.
---------------------------------------------------------------

1. 准备C++代码

在头文件中定义函数。这里需要注意的是不要直接在cpp文件中定义,在设置SWIG界面文件时需要通过头文件定义。

#ifndef EXAMPLE_H
#define EXAMPLE_H

#include<vector>
using namespace std;

vector<double> square(vector<double>vec);


#endif

头文件的文件名为example.h

函数定义在.cpp文件中:

#include "example.h"

vector<double> square(vector<double>vec){

    for (int i=0; i<vec.size(); i++){
        vec[i]=vec[i]*vec[i];
    }

    return vec;
}

文件名为example.cpp

2. 定义SWIG界面文件

// This line declares the module name as example. The module name 
// is what you'll use to import the generated module in the target 
// language (e.g., import example in Python).
%module example // interface to the example c++ library


// The %{ %} block is used to include the header files and any 
// other necessary C/C++ code that should be directly copied into 
// the generated wrapper code.
%{
    // includes the SWIG interface file for the std::vector class template.
    #include "example.h" 
%}

%include "std_vector.i";
using namespace std;

// creates a new template instantiation for std::vector<double>, naming
// it DoubleVector. This means that std::vector<double> will be wrapped 
// and available as DoubleVector in the target language.
%template(DoubleVector) vector<double>;

// This line includes the example.h header file again but this time in 
// the context of the SWIG processing. This inclusion tells SWIG to parse 
// and wrap the declarations in example.h according to the specified SWIG directives.
%include example.h

将文件存为example.i

3. 生成Python wrapper

如果没有安装SWIG,应首先在当前Python环境下安装SWIG:

pip install swig

然后执行如下命令行:

swig -c++ -python .\example.i

执行完毕后应该生成了example.pyexample_wrap.cxx两个文件。

4. 编写setup.py文件

#!/usr/bin/env python

from distutils.core import setup, Extension
# from setuptools import setup, Extension   # for python >3.12

example_module = Extension(
    '_example',
    sources = ['example_wrap.cxx', 'example.cpp']
    )

setup (
    name = 'example',
    version = '0.1',
    author      = "Bin Yang",
    description = """Simple swig example from docs""",
    ext_modules = [example_module],
    py_modules = ["example"],
    )

5. 编译生成可供调用的包

5.1 Ubuntu系统

执行如下命令:

python setup.py build_ext --inplace

测试时所使用的版本为Python 3.8。执行过后在当前文件夹下可以直接调用example包:

import example

example.square([1,2])

应该得到如下输出:

[1, 4]

5.2 Windows

在Windows系统下需要先安装微软的c++开发工具,总共约7GB大小!

然后执行与5.1节一样的命令。使用方法也相同。测试使用的为Python 3.9。

教程链接:

SWIG C++ python demo - YouTube

Everything not saved will be lost.
最后更新于 2024-07-11