[英]Calling C++ class functions from Ruby/Python
在我的特定情況下,我有一個復雜的類(一類類的類)要公開給腳本語言(也就是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年編寫的大米做文章的文章,我想要一個可能有用的指南(我運氣不太好)剛剛)
ASWELL:
我正在使用Linux(Ubuntu),但這是一個相互兼容的程序,因此我必須能夠在Windows和OS X上進行編譯
編輯:
我確實知道共享庫(dll等文件)存在,但是我不知道我是否可以擁有一個依賴於包含類的.hpp文件的庫。
您可以使用cython或Boost.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; }
可以使用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
那么Boost.Python呢?
您為什么不想使用SWIG?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.