chaquo / chaquopy

Chaquopy: the Python SDK for Android
https://chaquo.com/chaquopy/
MIT License
748 stars 127 forks source link

Use prebuild Python lib #1180

Open gmli opened 2 weeks ago

gmli commented 2 weeks ago

Hi,

For years I’ve been using crystax-ndk with the prebuilt libpython3.5m to embed Python in my Android app. Using it as a C lib like any other (but I need Python 3.10 now and crystax isn’t maintained).

My main issue is that I need to call (via JNI) some functions of the host application in the Python source code.

I’ve read the doc but it seems like chaquopy is able to call Java code but not directly the running application code, am I right ? Otherwise it would be ideal.

If it’s not possible, then I would like to use the prebuild Python lib from there https://repo.maven.apache.org/maven2/com/chaquo/python/target/3.10.13-0/ to embed the Python interpreter.

I’ve done it with success using crystax-ndk, but now with the official NDK I got this error :

java.lang.UnsatisfiedLinkError: dlopen failed: library "/Users/gludwig/git/tech.smag.regulatorymodule/regulatorymodule/build/intermediates/cxx/Debug/6d3wr1p2/obj/local/arm64-v8a/libpython3.10.so" not found: needed by /data/app/~~0Kigl3YzxOsteioiy_wuJQ==/tech.smag.regulatorymodule.app-5pyHSoApNEq-5BFm2UwIrQ==/base.apk!/lib/arm64-v8a/libpythonbridge.so in namespace classloader-namespace at java.lang.Runtime.loadLibrary0(Runtime.java:1077)

Here is my Android.mk : 

LOCAL_PATH :=$(call my-dir)

# Build libpythonbridge.so
include $(CLEAR_VARS)
LOCAL_MODULE := pythonbridge
LOCAL_SRC_FILES := pythonbridge.c
LOCAL_LDLIBS:= -llog
LOCAL_SHARED_LIBRARIES := python3.10
include $(BUILD_SHARED_LIBRARY)

# Include libpython3.10.so
include $(CLEAR_VARS)
LOCAL_MODULE    := python3.10
LOCAL_SRC_FILES := target-3.10.13-0-arm64-v8a/jniLibs/arm64-v8a/libpython3.10.so
LOCAL_EXPORT_CFLAGS := -I target-3.10.13-0-arm64-v8a/include/python3.10/
include $(PREBUILT_SHARED_LIBRARY)

If it’s not possible to access Kotlin functions of my app, could someone give me hints for why this error occured ? Thanks in advance.

Regards gml

mhsmith commented 1 week ago

It looks like libpythonbridge.so has somehow been linked against the absolute path of libpython3.10.so on your build machine, rather than simply "libpython3.10.so" as it should be.

But rather than debugging build systems, you would find it much easier to just use Chaquopy in the normal way, because it's absolutely capable of "calling directly the running application code". The usual approach would be:

gmli commented 1 week ago

Thank you, I’ll try the normal way as you described.

But you’re right for the linking, reading it with elfread shows the absolute path, while with crystax or with the old "python-android-support" it contains only the file name.

mhsmith commented 10 hours ago

I hope you managed to solve your issue; if you have any more questions, just post them below.