Windows10系统Python2.7通过Swig调用C++过程

我用的 python版本是2.7.12:

Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32

 

1, 下载Swig

  下载地址:http://www.swig.org/download.html,我下载了最新版本swigwin-4.0.0. 下载后直接解压,把 swig.exe 所在目录添加到系统环境变量 Path中。在 Command中输入 swig -version,如果出现版本号说明添加成功。

 

2,编写 c++代码

  头文件 example.h

 1 #pragma once
 2 
 3 #include <iostream>
 4 using namespace std;
 5 
 6 class Example {
 7 public:
 8 
 9     const char* getString();
10     void setString(const char* str);
11 };

  example.cpp

 1 #include "example.h"
 2 
 3 void Example::setString(const char* str)
 4 {
 5     cout<<str<<endl;
 6 }
 7 
 8 const char* Example::getString()
 9 {
10     return "hello";
11 }

 

3,编写 example.i 文件

1 %module Example
2 
3 %{
4 #include "example.h"
5 %}
6 
7 %include "example.h"

 

4,编写 setup.py 文件

1 from distutils.core import setup,Extension
2 test_module = Extension('_Example',sources = ['example_wrap.cxx','example.cpp'],)
3 setup(name = 'example',
4       version = '0.1',
5       author = '',
6       description = 'Simple swig example',
7       ext_modules = [test_module],
8       py_modules = ['example'],
9       )

 

5,运行命令 regedit 打开注册表,查看下列路径是否有该键值  productdir:VS安装目录\VC\Auxiliary\Build,如果没有则新建目录并添加键值。这个目录"VS安装目录\VC\Auxiliary\Build"其实是 vcvarsall.bat 文件所在目录,python要用到vcvarsall.bat。

\HKEY_CURRENT_USER\Software\Wow6432Node\Microsoft\VisualStudio\9.0\Setup\VC

因为我的VS安装在c:\vs2019,所以我设置 productdir:c:\vs2019\VC\Auxiliary\Build

 

6, 打开 Command,cd 到 example.i  文件所在目录,确保 c++文件和 example.i  文件在同一个目录下;输入下列命令:

  swig -python -c++ example.i

  产生文件 Example.py 和 example_wrap.cxx。

 

7,Command继续输入命令:

  python2 setup.py build_ext --inplace

 产生 _Example.pyd 文件。如果没有产生这个文件,查看错误原因,如果第 5 步没成功提示 cannot find vcvarsall.bat

 

8,Command 输入 Python2 进入 python环境:

>>> from Example import *
>>> ex = Example()
>>> ex.getString()
'hello'
>>> ex.setString("hello")
hello

说明:最好不要通过 Visual studio 来产生 pyd 文件,因为 python与 VC版本不匹配会出现各种错误提示。比如2.7.12需要MSC v.1500即VS2008版本。

MS VC++ 14.0 _MSC_VER = 1900 vs2015
MS VC++ 12.0 _MSC_VER = 1800 vs2013的编译器他的平台是v120
MS VC++ 11.0 _MSC_VER = 1700 vs2012的编译器他的平台是v110
MS VC++ 10.0 _MSC_VER = 1600 Visual C++ 2010
MS VC++ 9.0 _MSC_VER = 1500 Visual C++ 2008
MS VC++ 8.0 _MSC_VER = 1400 Visual C++ 2005
MS VC++ 7.1 _MSC_VER = 1310
MS VC++ 7.0 _MSC_VER = 1300
MS VC++ 6.0 _MSC_VER = 1200
MS VC++ 5.0 _MSC_VER = 1100

posted @ 2019-08-01 14:22  西北望射天狼  阅读(579)  评论(0编辑  收藏  举报