Skip to content

Instantly share code, notes, and snippets.

@lethosor
Last active July 6, 2017 02:25
Show Gist options
  • Save lethosor/02b038ad28b552752209f6f5f7ba90d3 to your computer and use it in GitHub Desktop.
Save lethosor/02b038ad28b552752209f6f5f7ba90d3 to your computer and use it in GitHub Desktop.
Python DFHack test
include/python
*.o
embed
libpython*
  1. Link libpython to "libpython3.6.dylib" in the current folder
  2. Link python include directory to "include/python"
  3. make
#include <dlfcn.h>
#include <iostream>
#include <python/Python.h>
using namespace std;
PyObject *dfhack_print(PyObject *self, PyObject *args) {
cout << "dfhack_print()" << endl;
Py_RETURN_NONE;
}
PyObject *dfhack_call(PyObject *self, PyObject *args) {
ssize_t len = PyTuple_Size(args);
cout << "dfhack_call(): " << len << " arguments" << endl;
for (ssize_t i = 0; i < len; i++) {
PyObject *obj = PyTuple_GetItem(args, i);
PyTypeObject *type = Py_TYPE(obj);
cout << " arg " << i << " = " << obj << ", type: " << type->tp_name << endl;
if (PyLong_Check(obj)) {
cout << " as long: " << PyLong_AsLong(obj) << endl;
}
}
Py_RETURN_NONE;
}
PyMethodDef dfhack_methods[] = {
{"print", dfhack_print, METH_VARARGS, "help"},
{"call", dfhack_call, METH_VARARGS, 0},
{0, 0, 0, 0}
};
PyModuleDef dfhack_module = {
PyModuleDef_HEAD_INIT, "dfhack", nullptr, -1, dfhack_methods,
0, 0, 0, 0
};
PyObject* dfhack_init() {
cout << "dfhack_init" << endl;
return PyModule_Create(&dfhack_module);
}
int main() {
cout << "bind ok" << endl;
PyImport_AppendInittab("dfhack", dfhack_init);
Py_SetProgramName(Py_DecodeLocale("dfhack", nullptr));
Py_Initialize();
cout << PyImport_ImportModule("dfhack") << endl;
cout << PyImport_ImportModule("sys") << endl;
cout << PyImport_ImportModule("math") << endl;
cout << PyImport_ImportModule("os.path") << endl;
PyRun_SimpleString("print('hello')");
PyRun_SimpleString("import dfhack;print(dfhack.print())");
PyRun_SimpleString("print(dir(dfhack))");
PyRun_SimpleString("dfhack.call(5, 'a', None, True, False, 3.2,(),[],{},set())");
return 0;
}
CXXFLAGS = -std=c++11 -I./include
# LDFLAGS = -L. -lpython3.6 -lstdc++
LDFLAGS = -lstdc++
all: embed
embed: embed.o
.PHONY: clean
clean:
rm -f embed *.o
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment