从Ruby/Python调用C++类函数

bbo*_*577 6 c++ ruby python embedding

在我的特定情况下,我有一个复杂的类(一类类的类),我想要暴露给脚本语言(又名Ruby).相反,直接传递那个复杂的类,有人给了我一个想法,就是像Ruby这样的脚本语言开放一些函数,这看起来更简单.我见过赖斯,但我见过的唯一例子是使用简单的函数来增加某些东西,而不是与类接口.

为简单起见,我有一个简单的类,包含我想要公开的函数:

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);}
};
Run Code Online (Sandbox Code Playgroud)

也:

我不想只是链接到SWIG的下载页面,或者是一篇文章解释如何用2010年编写的米饭来做这个,我想要一个可能有用的指南(我运气不好)还没)

藏汉:

我正在使用Linux(Ubuntu),但这是一个交叉兼容的程序,所以我必须能够在Windows和OS X上编译

编辑:

我知道存在共享库(dll和so文件),但我不知道我是否可以拥有一个依赖于包含类的.hpp文件的库.

jor*_*b87 2

您可以使用cythonBoost.Python从 python 调用本机代码。由于您使用的是 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; }
Run Code Online (Sandbox Code Playgroud)

可以使用 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);
}
Run Code Online (Sandbox Code Playgroud)

这段代码可以编译成静态库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
Run Code Online (Sandbox Code Playgroud)