swig c++ python

最近帮运营用 python 做实时提取玩家数据的脚本。鉴于已有后台的 lua 和 c++ 的 api 相互调用是使用 swig,python 也就直接使用 swig 了。

swig 的官网和中文官网:swig 官网 swig 中文

网上写的比较好的博客也有:好的博客

先说下代码流程:

//test.cpp
#include <iostream>
#include "test.h"
using namespace std;
int numCount = 1;
void AddNum()
{
//      int i = 1;
        while(numCount){
                cout<<"numCount: "<<numCount<<endl;
                if (numCount==10)
                        numCount=1;
                else
                        numCount++;
                sleep(1);
        }
}

int GetNum()
{
        return numCount;
}
//test.h
#include <iostream>
#include <unistd.h>
extern int numCount;

void AddNum();
int GetNum();
//test.i
%module test
%{
        #include "test.h"

%}
        %include "test.h"

编译命令:

swig -python -c++ test.i
g++ -c -fpic test.cpp test_wrap.cxx -I/usr/include/python2.6 -Xlinker -export-dynamic
g++ -fpic -shared test.o test_wrap.o -o _test.so -Xlinker -export-dynamic

验证:

Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> test.GetNum()
1

这样的话在 python 中传入玩家 id 就可以运行 c++ 程序中的实时数据了。

用法等等官网都有很详细的说明,但是遇到的问题很多,swig 再不同平台编译的时候有很多差别,官网上也给出了三种操作系统的编译方式,然而在实际操作中不同的 linux 版本会带来不同的错误。

比如 错误:Python.h:没有那个文件或目录 就需要执行 sudo yum install python-devel

还有两个 需要注意的编译选项:

-fpic  (https://www.cnblogs.com/cswuyg/p/3830703.html)
 -Xlinker -export-dynamic  (https://blog.csdn.net/jq0123/article/details/1340839)
如果这两个选项不加也会出现编译通过,但导入模块的时候出错。
关于c++ linux下编译的基础知识: 在linux环境下编译C++ 程序


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值