Mik*_*eir 5 c++ lua swig squirrel
我一直在研究这个问题几个月,现在想要真正想出一个适当的解决方案来处理用成员函数/创建新的用户定义类(以及那些类的实例)的情况C++ 11项目中运行时的属性.
到目前为止,我一直在使用SWIG(以前使用Python,现在使用Lua,探索Squirrel).就像我到目前为止遇到的所有C++绑定/嵌入库(Luna*,luabinder,luabind,OOLua,Sqrat/Sqext,Squall)一样,所有人都希望在代码执行之前用C++预定义类,因为它们要么依赖于预处理器指令或模板.
所以我的问题是,是否有任何库使用更程序化的方法来包装语言,或者是否有任何像Lua或Squirrel这样的好的教程/示例,建议用于处理自定义类的创建有自定义成员和功能?一些方向将不胜感激.
即使只是一个很好的例子,展示如何使用函数和属性创建一个自定义类,在Lua,Squirrel中,通过它们各自的C++ API而不使用宏/模板/动态生成的代码,将非常有用.
编辑:我已经创建了一个Instance包含std::vector成员键/值对的类,以及一个标识类型的成员,因此可以查找函数.但是,在没有使用静态代码的情况下,在Lua/Squirrel中创建简单类的文档很少.
编辑2:我想要一个适用于任何平台的解决方案,无需动态链接.
创建从某些现有 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() |
+--------------+
Run Code Online (Sandbox Code Playgroud)
下面是使用 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);
}
Run Code Online (Sandbox Code Playgroud)
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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
518 次 |
| 最近记录: |