57 #include "config/have_protobuf.hh"
63 #include <google/protobuf/stubs/common.h>
68 namespace py = pybind11;
72 #define PyCC(x) (const_cast<char *>(x))
77 const char *modpath,
const unsigned char *code,
int zlen,
int len)
78 : filename(filename), abspath(abspath), modpath(modpath), code(code),
83 if (
string(
modpath) ==
string(
"importer"))
103 Bytef marshalled[
len];
105 int ret = uncompress(marshalled, &unzlen, (
const Bytef *)
code,
zlen);
107 panic(
"Could not uncompress code: %s\n", zError(ret));
108 assert(unzlen == (uLongf)
len);
110 return PyMarshal_ReadObjectFromString((
char *)marshalled,
len);
146 for (;
i != end; ++
i)
147 if (!(*i)->addModule())
154 void (*init_func)(py::module &),
156 : initFunc(init_func), registered(false),
name(_name),
base(_base)
158 getMap()[_name] =
this;
162 void (*init_func)(py::module &))
163 : initFunc(init_func), registered(false),
name(_name),
base(
"")
165 getMap()[_name] =
this;
175 cprintf(
"Warning: %s already registered.\n",
name);
185 std::map<std::string, EmbeddedPyBind *> &
188 static std::map<std::string, EmbeddedPyBind *> objs;
192 #if PY_MAJOR_VERSION >= 3
201 py::module m_m5 = py::module(
"_m5");
202 m_m5.attr(
"__package__") = py::cast(
"_m5");
210 for (
auto &kv :
getMap()) {
211 auto &obj = kv.second;
212 if (obj->base.empty()) {
215 pending.push_back(obj);
219 while (!pending.empty()) {
220 for (
auto it = pending.begin(); it != pending.end(); ) {
224 it = pending.erase(it);
231 #if PY_MAJOR_VERSION >= 3
241 panic(
"Failed to add _m5 to Python's inittab\n");
265 GOOGLE_PROTOBUF_VERIFY_VERSION;
269 #if PY_MAJOR_VERSION >= 3
270 typedef std::unique_ptr<
wchar_t[], decltype(&PyMem_RawFree)> WArgUPtr;
273 v_argv.reserve(argc);
274 vp_argv.reserve(argc);
275 for (
int i = 0;
i < argc;
i++) {
276 v_argv.emplace_back(Py_DecodeLocale(_argv[
i], NULL), &PyMem_RawFree);
277 vp_argv.emplace_back(v_argv.back().get());
280 wchar_t **argv = vp_argv.data();
285 PySys_SetArgv(argc, argv);
288 PyObject *module = PyImport_AddModule(
PyCC(
"__main__"));
290 panic(
"Could not import __main__");
291 PyObject *dict = PyModule_GetDict(module);
300 result = PyRun_String(*command, Py_file_input, dict, dict);
311 google::protobuf::ShutdownProtobufLibrary();