Shiboken的资料真少,仅仅为了写一个小小的demo就大费周折。但不管怎样,经过几个月断断续续的了解,总算可以为纯C++的库和Qt的库创建python的绑定了。本文前提:
- 熟悉cmake,能够用cmake构建C++与Qt的程序和库
- 安装有Python和Shiboken的开发环境
- 安装有PySide和Qt4(4.6及以上)的开发环境
- 注意:若在windows下,Shiboken和PySide开发环境需要自己编译
接下来记录两个例子:(本文例子仅在Windows和Ubuntu环境下进行过测试)
创建C++库的绑定
步骤:
- 创建一个普通的 C++ 的库 foo.dll 或 libfoo.so
- 使用shiboken生成胶水代码
- 编译胶水代码生成绑定库 foo.pyd 或 foo.so
- 编写python程序进行测试
看一下本例用到的所有文件:|-- CMakeLists.txt||-- libfoo||-- CMakeLists.txt||-- foo.h|`-- foo.cpp||-- foobinding||-- CMakeLists.txt||-- foo|||-- CMakeLists.txt|||-- global.h||`-- typesystem_foo.xml|`-- tests| |-- CMakeLists.txt| `-- test_foo.py顶层的CMakeLists.txt 文件内容如下:cmake_minimum_required(VERSION 2.8)add_subdirectory(libfoo)add_subdirectory(foobinding)enable_testing()
libfoo
libfoo 中是我们原始的需要绑定的C++代码,可以快速一下这3个文件
project(libfoo)set(LIB_SRC foo.cpp)add_definitions("-DLIBFOO_BUILD")add_library(libfoo SHARED ${LIB_SRC})set_target_properties(libfoo PROPERTIES OUTPUT_NAME "foo")
#ifndef FOO_H#define FOO_H#if defined _WIN32#if LIBFOO_BUILD#define LIBFOO_API __declspec(dllexport)#else#define LIBFOO_API __declspec(dllimport)#endif#else#define LIBFOO_API#endifclass LIBFOO_API Math{public:Math(){}~Math(){}int squared(int x);};#endif // FOO_H
#include "foo.h"int Math::squared(int x){return x * x;}这部分没有什么特别的东西,直接看绑定部分