Windows中使用SWIG的Python调用C/C++的方法

平台:window 7, Visual Studio 2015, Python

1. 首先在 下载swig安装包,把文档也下载下来以备日后使用。解压安装包到任意路径,路径中最好不要带空格。

2. 制作源文件和swig接口文件,我的文件如下

/* jsample.h */
#ifndef JSAMPLE_H
#define JSAMPLE_H
//void cHelloWorld();
int compute(int a, int b);
#endif
/* jsample.cpp */
#include <iostream>
#include "jsample.h"
using namespace std;
  
int compute(int a, int b)
{
    int temp = (a+b)*(a-b);
    return temp;
}
/* File : jsample.i */
%module jsample
 
%inline %{
#include "jsample.h"
%}
int compute(int a,int b);

3. 使用swig生成部分文件

把swig.exe所在的路径添加到系统环境变量path中 swig -c++ -python jsample.i

如果是C语言的话就是swig -python jsample.i

在当前目录下会生成两个文件jsample_wrap.cxx和jsample.py。

4. 配置Visual Studio 的文件路径

配置环境变量

PYTHON_INCLUDE : D:Program Filespython3include

PYTHON_LIB : D:Program Filespython3libspython37.lib

5. 使用Visual Studio (我的2015)编译文件

新建一个 Win32 Console Application 工程,在向导中点next,Application type选择 DLL ,在 Additional options 中选择 Emppty project。

把 jsample.h, jsample.cpp, jsample_wrap.cxx, jsample.i 拖入到工程中,文件自动放置到对应的位置。

VS 设置如下

    设置Configration为 Release, Platform为 x64。(和安装的Python位数保持一致) C/C++ > 常规 > 附加包含目录 增加:$(PYTHON_INCLUDE ); 连接器 > 输入 > 附加依赖项 增加:$(PYTHON_LIB ) 常规 > 目标文件名 修改为 _$(ProjectName) 常规 - 目标文件拓展名 修改为 .pyd 设置输入目录:参考$(ProjectDir)、$(SolutionDir) 等确定输出文件位置

最后 Build Solution ,在 Release 文件夹中会生成 _jsample.pyd。

#!/usr/bin/env python
# -*- coding: cp936 -*-
# runme.py
from __future__ import division
  
import jsample
print(this is the test running.
)
aa = jsample.compute(5,2)
print(aa)
raw_input("press the enter key to exit.")

https://bbs..net/topics/300099682

http://www.cnblogs.com/kaituorensheng/p/4464117.html

https://blog..net/peter_teng/article/details/9716421

经验分享 程序员 微信小程序 职场和发展