在我的特定情况下,我有一个复杂的类(类的类),我想将其公开给脚本语言(又名 Ruby)。与其直接传递那个复杂的类,有人给了我一个想法,就是将一些函数开放给像 Ruby 这样的脚本语言,这看起来更简单。我见过 Rice,但我见过的唯一例子是使用简单的函数来乘以某些东西,而不是与类交互。
为简单起见,我有一个简单的类,其中包含我想公开的函数:
class Foo
{
private:
//Integer Vector:
std::vector<int> fooVector;
public:
//Functions to expose to Ruby:
void pushBack(const int& newInt) {fooVector.push_back(newInt);}
int& getInt(const int& element) {return fooVector.at(element);}
};
还有:
我不想只提供指向 SWIG 下载页面的链接,或者一篇 2010 年写的解释如何用大米做到这一点的文章,我想要一个可能有用的指南(我还没有运气还不错)
还有:
我使用的是 Linux (Ubuntu),但这是一个交叉兼容的程序,所以我必须能够在 Windows 和 OS X 上编译
编辑:
我知道共享库存在(dll 和 so 文件),但我不知道我是否可以拥有一个依赖于包含类的 .hpp 文件的库。
最佳答案
您可以使用 cython或 Boost.Python从 python 调用 native 代码。由于您使用的是 C++,我建议您查看 Boost.Python它提供了一种非常自然的方式来为 Python 包装 C++ 类。
作为示例(接近您提供的内容),请考虑以下类定义
class Bar
{
private:
int value;
public:
Bar() : value(42){ }
//Functions to expose to Python:
int getValue() const { return value; }
void setValue(int newValue) { value = newValue; }
};
class Foo
{
private:
//Integer Vector:
std::vector<int> fooVector;
Bar bar;
public:
//Functions to expose to Python:
void pushBack(const int& newInt) { fooVector.push_back(newInt); }
int getInt(const int& element) { return fooVector.at(element); }
Bar& getBar() { return bar; }
};
double compute() { return 18.3; }
这可以使用 Boost.Python 包装成 python
#include <boost/python.hpp>
BOOST_PYTHON_MODULE(MyLibrary) {
using namespace boost::python;
class_<Foo>("Foo", init<>())
.def("pushBack", &Foo::pushBack, (arg("newInt")))
.def("getInt", &Foo::getInt, (arg("element")))
.def("getBar", &Foo::getBar, return_value_policy<reference_existing_object>())
;
class_<Bar>("Bar", init<>())
.def("getValue", &Bar::getValue)
.def("setValue", &Bar::setValue, (arg("newValue")))
;
def("compute", compute);
}
这段代码可以编译成静态库MyLibrary.pyd
并像这样使用
import MyLibrary
foo = MyLibrary.Foo()
foo.pushBack(10);
foo.pushBack(20);
foo.pushBack(30);
print(foo.getInt(0)) # 10
print(foo.getInt(1)) # 20
print(foo.getInt(2)) # 30
bar = foo.getBar()
print(bar.getValue()) # 42
bar.setValue(17)
print(foo.getBar().getValue()) #17
print(MyLibrary.compute()) # 18.3
关于python - 从 Ruby/Python 调用 C++ 类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30602088/