到目前为止,我一直在使用 SWIG(以前使用 Python,现在使用 Lua,探索 Squirrel)。与我迄今为止遇到的所有 C++ 绑定/嵌入库(Luna*、luabinder、luabind、OOLua、Sqrat/Sqext、Squall)一样,它们都希望您的类在代码执行之前在 C++ 中预定义,因为它们要么依赖于预处理器指令或模板。
创建从某些现有 C++ 类派生的类是将新类引入正在运行的 C++ 程序的唯一方法(据我所知)。如果没有动态编译实际的 C++ 源代码并加载生成的库,就无法物理添加新类。下一个最好的事情是在 C++ 中创建一个包装 Python(Lua 等)对象的代理对象,并使该 Python(Lua)对象成为一个类的实例,该类扩展镜像到 Python(Lua)端的现有 C++ 类。
C++
+---------+ mirrors +--------------+
| class X | ...............................> | class X |
+---------+ | mirrored to |
| | Python |
| inherits +--------------+
v inherits |
+-----------------+ v
| class X_Wrapper | references +--------------+
| | python obj -------------------------> | class CX(X): |
+-----------------+ | def met() |
+--------------+
下面是使用 Python 扩展 C++ 类的示例,使用 boost::python 作为桥梁。
C++方面:
#include <boost/python.hpp>
#include <iostream>
using namespace boost::python;
// this is the interface we will implement in Python
struct World
{
virtual std::string greet() = 0;
virtual ~World() {}
};
// this is a helper class needed to access Python-overrided methods
struct WorldWrap : World, wrapper<World>
{
std::string greet()
{
return this->get_override("greet")();
}
};
// This function tests our class implemented in Python
std::string test(World* w)
{
std::cout << "Calling w->greet() on some World-derived object\n";
return w->greet();
}
// This is what the Python side will see
BOOST_PYTHON_MODULE(hello)
{
class_<WorldWrap, boost::noncopyable>("World")
.def("greet", pure_virtual(&World::greet));
def("test", test);
}
Python端:
import hello
class HomeWorld(hello.World):
""" Implements a function defined in C++ as pure virtual """
def greet(self):
return "howdy"
home = HomeWorld()
print (hello.test(home))