SWIG
选择相应版本后点击,然后在Files下下载zip文件,新版本如果弹出注册页面,可以多刷新几次
Release
windows10
Windows_installation
直接下载对应版本的zip文件后,如swigwin-4.0.2.zip
,解压后,后台运行既可查看版本
./swig.exe -version
使用时可以添加环境变量,或者使用CMakeLists配置
Linux (Ubuntu18.04)
unix_installation
下载对应版本的tar.gz
文件,如:swig-4.0.2.tar.gz
tar -zxvf swig-4.0.2.tar.gz
解压后执行以下命令
cd swig-4.0.2
bash ./configure --prefix=/usr/local/swig-4.0.2 --without-pcre
make
make install
其中--prefix
表示安装路径,--without-pcre
表示不依赖pcre
,更多细节可以运行./configure --help
查看
Doc HTML
test.h
#include
int add(int a, int b);
int sub(int a, int b);
test.cpp
#include "test.h"
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
test.i
%module test
%{
#define SWIG_WITH_INT //python needs init file
#include "test.h"
%}
%include "test.h"
生成pythonTest_warp.cxx
文件
swig -c++ -python -o pythonTest_warp.cxx test.i
完成后目录下会生成pythonTest_warp.cxx 和 test.py 文件
编写setup.py
文件,然后生成相应库文件
setup.py
from distutils.core import setup, Extension
test_module=Extension("_test",
sources=["pythonTest_warp.cxx",
"test.cpp"],
)
setup(name="test",
version="0.1",
author="ZJH",
description="Simple swig c++ to python",
ext_modules=[test_module],
py_modules=["test"]
)
python setup.py build
测试
testrun.py
>>> import test
>>> test.add(1, 2)
3
>>> test.sub(1, 0)
1
编写CMakeLists.txt
文件
cmake_minimum_required(VERSION 3.10)
# set the project name
project(SwigTest VERSION 1.0)
# set verbose makefile
set(CMAKE_VERBOSE_MAKEFILE ON)
# specify the C++ standard
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)
add_library(testLib test.cpp)
if(WIN32)
include_directories(
E:/Anaconda/Anaconda3/include
)
link_directories(
E:/Anaconda/Anaconda3/libs/
)
else()
include_directories(
/usr/include/python3.6
)
link_directories(
/usr/bin/
)
endif()
add_library(${PROJECT_NAME} SHARED
pythonTest_warp.cxx
)
# set(PYTHON_INCLUDE_DIRS E:/Anaconda/Anaconda3/include)
# set(PYTHON_LIBRARIES E:/Anaconda/Anaconda3/libs/python36.lib)
# message(${PYTHON_LIBRARIES})
# target_link_libraries(${PROJECT_NAME} ${PYTHON_LIBRARIES})
if(WIN32)
target_link_libraries(${PROJECT_NAME} python36 testLib)
else()
target_link_libraries(${PROJECT_NAME} python3.6m testLib)
endif()
set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "_")
if(WIN32)
set_target_properties(${PROJECT_NAME} PROPERTIES SUFFIX ".pyd")
else()
set_target_properties(${PROJECT_NAME} PROPERTIES SUFFIX ".so")
endif()
set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME "test")