SWIG ---- Python调用C++

SWIG ---- Python 调用C++

使用 SWIG(Simplified Wrapper and Interface Generator) 实现在Python中调用C++的代码.

C++ Source Code

// service.h
class Service
{
public:
	Service();
	int add(int a, int b);
};
// service.cpp
 #include "service.h"
 Service::Service()
 {
 }
 int add(int a, int b)
 {
 	return a + b;
 }

SWIG interface code

// service.i
%module service;
%{
#include "service.h"
%}
%include "service.h"

Steps

1 使用SWIG生成service.py 和 service_wrap.cxx

In order to compile the C/C++ wrappers, the compiler needs the Python.h header file.

swig -c++ -python service

2 编译C++源码生成 service.o

On some platforms, you could also need to generate position-independent code (PIC), by using a compiler option such as -fPIC. Notably, the x86_64 (Opteron and EM64T) platform requires it, and when using the GNU Compiler Suite, you will need to modify the previous example as follows:

g++ -c -fPIC service.h service.cpp

3 编译service_wrap.cxx生成service_wrap.o

g++ -c -fPIC service_wrap.cxx -I/usr/local/include/python2.7

4 链接service.o与service_wrap.o生成动态库_servic.so

g++ -shared service.o service_wrap.o -o _service.so

测试

// test.py
import service

ser = service.Service()
print ser.add(1,2)
python test.py

参考资料

链接: SWIG and Python

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值