I try to use a prototype python code in an Android app and I found Chaquopy as a possible library.
The documentation is a little sparse, so I want to clarify: Can I call my self-written python methods (incl. passing variables) in Android Java code with Chaquopy?
If yes, would it be possible to see an example how this works? Seeing an example which especially passes complex objects (so not only strings) I would really appreciate.
Thanks!
Yes, you can call your own Python code exactly like library code. Just place your Python files in the appropriate directory as the documentation describes.
I'm not sure what kind of "complex objects" you mean, but here are some examples of passing various types of objects to a Python function f
within a file mod.py
:
Python py = Python.getInstance();
PyObject mod = py.getModule("mod");
// If the function knows what methods and attributes to use, Java objects
// can be passed directly.
mod.callAttr("f", someJavaObject);
// If the function expects an iterable, Java arrays can be passed directly.
mod.callAttr("f", new String[] {"one", "two", "three"});
// If the function expects a dict, it can be created as follows.
PyObject builtins = py.getBuiltins();
PyObject d = builtins.callAttr("dict");
d.callAttr("__setitem__", 1, "a");
d.callAttr("__setitem__", 2, "b");
mod.callAttr("f", d);