Skip to content

Commit

Permalink
working calling python
Browse files Browse the repository at this point in the history
  • Loading branch information
mike dupont committed Dec 6, 2023
1 parent 2f3ea04 commit 1c86146
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions embedding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
print("hello llama.cpp")
56 changes: 56 additions & 0 deletions plugin_python.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#include <boost/python.hpp>
#include <iostream>
#include <frameobject.h>
#include <string>

class Base {
public:
Base() : mName("Base") {}
Base(const std::string& name) : mName(name) {}
virtual ~Base() {}
std::string name() const
{ return mName; }
private:
std::string mName;
};


using namespace boost::python;

#if PY_MAJOR_VERSION >= 3
# define INIT_MODULE PyInit_mymodule
extern "C" PyObject* INIT_MODULE();
#else
# define INIT_MODULE initmymodule
extern "C" void INIT_MODULE();
#endif


int call_python()
{
try {
PyImport_AppendInittab((char*)"mymodule", INIT_MODULE);
Py_Initialize();
object main_module = import("__main__");
dict main_namespace = extract<dict>(main_module.attr("__dict__"));
object mymodule = import("mymodule");

main_namespace["precreated_object"] = Base("created on C++ side");
exec_file("embedding.py", main_namespace, main_namespace);
} catch (error_already_set& e) {
PyErr_PrintEx(0);
return 1;
}
return 0;
}


using namespace boost::python;

BOOST_PYTHON_MODULE(mymodule)
{
class_<Base>("Base")
.def("__str__", &Base::name)
;
}

0 comments on commit 1c86146

Please sign in to comment.