dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.19k stars 1.57k forks source link

Dart VM shared library loading: how to get a java Context? / How to access Java from C library loaded with Flutter FFI #46027

Open lzunsec opened 3 years ago

lzunsec commented 3 years ago

Sorry but this is a highly specific question about the VM, I triged glitter but couldn't get help as this is very specific.

Some libraries, like JUCE (juce.com), requires this to be called on startup:

public native static void initialiseJUCE (Context appContext);

This calls C++ code with Java Context.

What if I want to load Juce with FFI directly through Flutter on Android? I want to use FFI so I have direct access to the C functions.

However, it's unclear how shared library loading on Dart VM occurs on Android. How would I get this Context from the Dart VM?

I bet Dart won't call JNI_Onload so I can register some java function that gets the context:

JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {

Is it even possible to access JavaVM though a library loaded from Dart VM?

bayo-code commented 3 years ago

To do this, just define JNI_OnLoad in your shared library and use the JavaVM object passed in there... Make sure to call System.loadLibrary to load your shared object in Java before anything. Either you do it by extending the Application class or in a static block inside of your Activity. Either way, load the library before Dart does so that the JNI_OnLoad gets called and your other libraries get initialized

PasqualeTotaro commented 7 months ago

@lzunsec did you ever find a solution to this?