Skip to content

Instantly share code, notes, and snippets.

@natfarleydev
Created December 3, 2015 10:27
Show Gist options
  • Save natfarleydev/dcf3f6851f524935cf67 to your computer and use it in GitHub Desktop.
Save natfarleydev/dcf3f6851f524935cf67 to your computer and use it in GitHub Desktop.
#import <iostream>
#import <TPython.h>
#import <TString.h>
#import <vector>
#import <string>
Int_t pickle_std_string_vector(std::vector<std::string> string_vec = { "foo", "bar"}, std::string pickle_filename = "tmp.p") {
TPython p = TPython();
p.Exec("import pickle");
p.Exec("list_to_pickle = []");
for(std::string& i: string_vec) {
p.Exec((std::string("list_to_pickle.append(\"")+i+std::string("\")")).c_str());
}
p.Exec((std::string("pickle.dump(list_to_pickle, open(\"")+pickle_filename+std::string("\", \"w\"))")).c_str());
return 0;
}
std::vector<std::string> unpickle_std_string_vector(std::string pickle_filename = "tmp.p") {
TPython p = TPython();
p.Exec("import pickle");
p.Exec((std::string("unpickled_list = pickle.load(open(\"")+pickle_filename+std::string("\", \"r\"))")).c_str());
p.Exec("return_vector_py = ROOT.std.vector(\"std::string\")()");
p.Exec(std::string("for i in unpickled_list: return_vector_py.push_back(i)").c_str());
TPyReturn pyReturn = p.Eval("return_vector_py");
std::vector<std::string> * _ = (std::vector<std::string> *)(void *)pyReturn;
std::vector<std::string> return_vector = *_;
return return_vector;
}
@natfarleydev
Copy link
Author

This could do with templating to pickle anything, however creating objects into python could be tricky. Could be solved by using a std::string for the ROOT class and a std::string for the python class in the arguments of the function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment