我目前正在进行一个项目,我们的一个团队正在设计一款游戏,我们所有人都精通 Ruby,并且我们中的一些人(但不是全部)精通 C++。 最初我们用 ruby 制作后端,但为了提高速度,我们将其移植到 c++。后端的C++端口与原始Ruby代码具有完全相同的功能和算法。 然而,我们仍然有一堆 ruby 代码可以做有用的事情,但我们不想将其全部移植,因此我们希望继续使用 ruby 代码并从 c++ 类获取数据。这不现实吗? 我们的第一个想法是我们可以将一些数据结构保存在 XML 或 Redis 之类的文件中并调用它,但一些开发人员不喜欢这个想法。 我们不需要在代码的不同部分之间传递任何特别复杂的数据结构,只需要元组、字符串和整数。 有什么方法可以集成 ruby 代码,以便它可以本地调用 c++ 东西吗? 我们需要嵌入代码吗?我们需要做一个 ruby 扩展吗?如果是的话,您可以建议什么好的资源/教程吗?
例如,假设我们在 C++ 后端中有一些这样的代码:
class The_game{
private:
bool printinfo; //print the player diagnostic info at the beginning if true
int numplayers;
std::vector<Player*> players;
string current_action;
int action_is_on; // the index of the player in the players array that the action is now on
//more code here
public:
Table(std::vector<Player *> in_players, std::vector<Statistics *> player_stats ,const int in_numplayers);
~Table();
void play_game();
History actions_history;
};
class History{
private:
int action_sequence_number;
std::vector<Action*> recent_actions;
public:
void print_history();
void add_action(Action* the_action_to_be_added);
int get_action_sequence_number(){ return action_sequence_number;}
bool history_actions_are_equal();
int last_action_size(int street,int number_of_actions_ago);
History();
~History();
};
有没有办法通过 ruby 中的 The_game 对象本地调用 actions_history 中的某些内容? (原始 ruby 代码中的对象都具有相同的名称和功能)
我的意思是:
class MyRubyClass
def method1(arg1)
puts arg1
self.f() # ... but still available
puts cpp_method.the_current_game.actions_history.get_action_sequence_number()
end
# Constructor:
def initialize(arg)
puts "In constructor with arg #{arg}"
#get the c++ object here and call it cpp_method
end
end
这可能吗?如有任何意见或建议,我们将不胜感激。
最佳答案
你可以use the Ruby C API创建与 C++ 类接口(interface)的扩展或 SWIG至 create a wrapper the C++ class .
关于c++ - 让 C++ 和 Ruby 共享公共(public)类的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2902752/