Best way to have common class shared by both C++ and Ruby?
I am currently working on a project where a team of us are designing a game, all of us are proficient in ruby and some (but not all) of us are proficient in c++. Initially we made the backend in ruby but we ported it to c++ for more speed. The c++ port of the backend has exactly the same features and algorithms as the original ruby code. However we still have a bunch of code in ruby that does useful things but we would rather not have to port it 开发者_运维技巧all, so we want to keep using the ruby code and get data from the c++ classes. Is this unrealistic? Our first thought was that we could save some of the data structures in something like XML or redis and call that, but some of the developers don't like that idea. We don't need any particularly complex data structures to be passed between the different parts of the code, just tuples, strings and ints. Is there any way of integrating the ruby code so that it can call the c++ stuff natively? Will we need to embed code? Will we have to make a ruby extension? If so are there any good resources/tutorials you could suggest?
For example say we have some code like this in the c++ backend:
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();
};
Is there any way to natively call something in the actions_history via The_game object in ruby? (The objects in the original ruby code all had the same names and functionality)
By this I mean:
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
Is this possible? Any advice or suggestions are appreciated.
You could use the Ruby C API to create an extension that interfaces with the C++ class or SWIG to create a wrapper the C++ class.
For creating ruby extensions you also might want to have a look at:
- Rice
- RubyInline
精彩评论