Embeding Python & Extending Python with FFPython
Introduction
ffpython is a C++ lib, which is to simplify tasks that embed Python and extend Python. As the author, I am a developer for MMO server. Mainly I use C++ to implement part that needs to response user's requests in realtime, while other logic part that needs to be modified frequently is implemented by Python. Python makes it possible to reload our part of the server when the server is running. Python is so easy that even my colleague with no programing skills can implement some npc script. When I was first in charge of integrating Python runtime interpreter to our C++ server, I used Boost.python. Somehow Boost.python helped me solve most problems about Python API especially parts of Python reference. But Boost.python is not perfect.
- When exception happens while invoking python function by boost.python, boost.python doesn't provide interface to fetch traceback information.
- Boost python is a big lib to some extent. Someone will find it much difficult who just wants to try to experience how embedding Python works.
- Boost.pyhon supports badly to extend python by using C++
staticfunction and class in runtime. Boost.python recommends to use dynamic library to extending python. - Someone who wants to learn example code using Python API will find it difficult to understand well boost.python codes, in my opinion.
- If you have the need to convert data between C++ STL container and python object builtin, you have to implement these codes yourself, while Python reference is so annoying.
FFPython
Firstly, I implemented it just for converting data between C++ STL container and python object. Some of my colleagues have writes a lot of code using Python API directly. But there is some trap in some Python API even engineers who have a lot of experience using Python may have lost. PyDict_SetItem will auto increase reference key and value arguments, but other Python builtin structure API like PyTuple_SetItem will not increase reference the argument. It will cause memory leak. So I wanted to wrap operations about converting data between C++ STL container and Python builtin structure. Finally, I found some elegant ways to wrap embedding Python and extending Python by C++ template skills. So that is how FFPyhton was born.
Embedding Python
Sometimes I think it's easier to show codes to readers here. ^_^. But it will be forbidden by administrator if I post lots of code.
O(n_n)O~. So see code files or Github.
When Embedding Python, such functions are most needed.
- Fetch global variable of python script(or module). This happens when you use Python script as config files.
- Call python function in script. That is the most useful interface. Two parts of it are important.
- It should be supported to use C++ builtin type and C++ STL container as argument.
- It should be supported to convert returned value of Python builtin types (like list, tuple, dict, string...) to C++ builtin types.
- Fetch exception information when exception happens, especially traceback information. Because of feature of dynamic type, exception regularly happens even in online server, let alone debugging time. ffpython will throw std exception when Python exception happens. So it is much easier to print or log traceback info by output
exception.what(). - ffpython support nine arguments.
- ffpython implemented by C++ template to wrap Python API. It is easy to understand how it works if you see the code.
printf("sys.version=%s\n",
ffpython.get_global_var<string>("sys", "version").c_str());
int a1 = ; float a2 = 3.14f; string a3 = "OhWell";
ffpython.call<void>("fftest", "test_base", a1, a2, a3);
vector<int> a1;a1.push_back();a1.push_back();
list<string> a2; a2.push_back("Oh");a2.push_back("Nice");
vector<list<string> > a3;a3.push_back(a2);
ffpython.call<bool>("fftest", "test_stl", a1, a2, a3);
typedef map<string, list<vector<int> > > ret_t;
ret_t val = ffpython.call<ret_t>("fftest", "test_return_stl");
Extending Python
ffpython recommends to register C++ function/class in runtime. It works to design and develop MMO game server. So that is common use for me. There are some key points when embedding Python.
- ffpython supports to register C++
staticfunction. C++ builtin types and STL container can be as arguments. - C++ class can be registered to Python.
Register C++ static function, all base type supported. Arg num can be nine.
static int print_val(int a1, float a2, const string& a3, const vector<double>& a4)
{
printf("%s[%d,%f,%s,%d]\n", __FUNCTION__, a1, a2, a3.c_str(), a4.size());
return ;
} ffpython_t ffpython;//("ext1");
ffpython.reg(&print_val, "print_val");
ffpython.init("ext1");
Register C++ class, Python can use it just like builtin types.
class foo_t{
public:
foo_t(int v_):m_value(v_){
printf("%s\n", __FUNCTION__);
}
virtual ~foo_t(){
printf("%s\n", __FUNCTION__);
}
int get_value() const { return m_value; }
void set_value(int v_) { m_value = v_; }
void test_stl(map<string, list<int> >& v_)
{
printf("%s\n", __FUNCTION__);
}
int m_value;
};
class dumy_t: public foo_t
{
public:
dumy_t(int v_):foo_t(v_)
{
printf("%s\n", __FUNCTION__);
}
~dumy_t()
{
printf("%s\n", __FUNCTION__);
}
void dump()
{
printf("%s\n", __FUNCTION__);
}
};
static foo_t* obj_test(dumy_t* p)
{
printf("%s\n", __FUNCTION__);
return p;
}
void test_register_base_class(ffpython_t& ffpython)
{
ffpython.reg_class<foo_t, PYCTOR(int)>("foo_t")
.reg(&foo_t::get_value, "get_value")
.reg(&foo_t::set_value, "set_value")
.reg(&foo_t::test_stl, "test_stl")
.reg_property(&foo_t::m_value, "m_value");
};
Summary
- ffpython only one implements head file, it is easy to integrate to project.
- ffpython is simply wrap for Python API, so it is efficient.
- github: https://github.com/fanchy/ffpython
- python2.5 python2.6 python2.7, win / linux
- python3.x is being developed, but unfortunately, Python3.x API is so different to python2.x, even different between python3.2 and python3.3, Headache!!
Embeding Python & Extending Python with FFPython的更多相关文章
- 1 python学习——python环境配置
1 python学习--python环境配置 要学习python语言,光看书看教程还是不好,得动手去写.当然,不管学习什么编程语言,最佳的方式还在于实践. 要实践,先得有一个Python解释器来解释执 ...
- CentOS使用virtualenv搭建独立的Python环境-python虚拟环境
CentOS使用virtualenv搭建独立的Python环境-python虚拟环境 virtualenv可以搭建虚拟且独立的python环境,可以使每个项目环境与其他项目独立开来,保持环境的干净,解 ...
- python 运行python manege.py runserver时报错:“no module named djangorestframework” 的解决方案
python 运行python manege.py runserver时报错:“no module named djangorestframework” 的解决方案 importerror:no mo ...
- 翻译文章“AST 模块:用 Python 修改 Python 代码”---!!注意ironpathyon未实现此功能
https://github.com/upsuper/blog/commit/0214fdd084c4adf2de2ed9912d644fb59ce13a1c +Title: [翻译] AST 模块: ...
- Python学习(二) 运行Python,编译Python
无论windos还是Linux只要安装了python,配置好了环境变量,则在命令行输入python这个命令的时候就会进入交互模式.在这个模式下可以进行一些简单的python代码编写.退出可以使用exi ...
- Python:Python学习总结
Python:Python学习总结 背景 PHP的$和->让人输入的手疼(PHP确实非常简洁和强大,适合WEB编程),Ruby的#.@.@@也好不到哪里(OO人员最该学习的一门语言). Pyth ...
- Python 正则表达式 (python网络爬虫)
昨天 2018 年 01 月 31 日,农历腊月十五日.20:00 左右,152 年一遇的月全食.血月.蓝月将今晚呈现空中,虽然没有看到蓝月亮,血月.月全食也是勉强可以了,还是可以想像一下一瓶蓝月亮洗 ...
- Python和Python解释器
目录 Python介绍(了解) Python解释器发展史(了解) Python解释器(了解) CPython IPython PyPy Jython IronPython 安装Python解释器(掌握 ...
- Python之python的一些理解
应用领域: 1. 网络爬虫 2. 大数据分析与挖掘 3. 机器学习 4. web应用 5. 游戏开发 6. 自动化运维 入门学习网站: imooc,廖雪峰,黑马 环境变量 --- 就是告诉电脑,你的程 ...
随机推荐
- centos7 配置vnc
这是一个关于怎样在你的 CentOS 7 上安装配置 VNC 服务的教程.当然这个教程也适合 RHEL 7 .在这个教程里,我们将学习什么是 VNC 以及怎样在 CentOS 7 上安装配置 VNC ...
- mongoDB研究笔记:journaling保证意外故障下的数据完整性
mongoDB的Journaling日志功能与常见的log日志是不一样的,mongoDB也有log日志,它只是简单记录了数据库在服务器上的启动信息.慢查询记录.数据库异常信息.客户端与数据库服务器连接 ...
- 工资低的.Net程序员,活该你工资低
这两天博客园上关于“.Net工资低”的讨论挺多的,让我不禁想起一句话“拉不出屎来怪地球没引力”. 那些抱怨“做.Net工作三年了月薪才6千,我的同学做Java现在都一万二”的哥们,你问问自己“我会什么 ...
- ASP.NET 5中的静态文件处理
ASP.NET 5 与之前的 ASP.NET 相比,有着翻天覆地的变化.了解与熟悉它需要一个过程,而我选择的了解方式是一步一步从无而有手写一个简单的 ASP.NET 5 程序,然后根据遇到的问题进行学 ...
- 借助阿里AntUI元素实现两个Web页面之间的过渡——“Loading…”
今天遇到了这么个问题,如下: 功能需求:有两个页面A和B,点击A中的"确定"按钮,超链接到页面B,在跳转到B页面时出现“Loading”的样式. 需求分析:作为一个后端程序员,一开 ...
- JavaScript函数绑定
一个简单的函数绑定 在JavaScript与DOM交互中经常需要使用函数绑定,定义一个函数然后将其绑定到特定DOM元素或集合的某个事件触发程序上,绑定函数经常和回调函数及事件处理程序一起使用,以便把函 ...
- 仿Material UI框架的动画特效
Material UI是一款功能非常强大,界面却十分清新简洁的CSS框架,Material UI利用了Google的Material Design 全新设计语言,并且让每一个UI组件都变得非常独立,因 ...
- [Python爬虫] Selenium+Phantomjs动态获取CSDN下载资源信息和评论
前面几篇文章介绍了Selenium.PhantomJS的基础知识及安装过程,这篇文章是一篇应用.通过Selenium调用Phantomjs获取CSDN下载资源的信息,最重要的是动态获取资源的评论,它是 ...
- 1121 if条件语句练习--输入年月日判断执行
<script type="text/javascript"> var a=prompt("请输入一个年","请输入年份"); ...
- debian7.8 安装 chm
一.CHMSEE 这个比较常见了,呵呵. 安装: sudo apt-get install chmsee 之后在应用程序附件中就可以看到了. 问题1: 启动不了或者出现 chmsee: error w ...