#jni — Public Fediverse posts
Live and recent posts from across the Fediverse tagged #jni, aggregated by home.social.
-
Создаем Java обертку для C++ класса в Android приложении, а также реализуем обратные вызовы из нэйтива
Кратко расскажу о себе и о том, зачем возникла необходимость в подобном. Я более десяти лет пишу приложения под Android, около 5 лет под IOS, и сейчас переношу свои наработки под десктопы. Приложения мои предназначены для сисадминов, это SSH клиент, сетевые сканеры и тд. В общем, самое сложное - не сам интерфейс, а то, что под капотом. Когда я лишь начинал, я думал, что остановлюсь на платформе Android и стал пилить все на Java. Но затем осознал свою ошибку и исправил ее. На данный момент все мои приложения состоят из двух частей: общего для всех систем ядра на С++ и платформозависимого интерфейса, написанного на Java/Swift/C++ в зависимости от системы. Оговорюсь сразу, эта статья будет лишь своего рода вступлением. Я покажу, как работать с объектно-ориентированным кодом на C++ в Java оболочке (в JNI нам доступен экспорт С функций). Инициализировать объект, делать из него вызовы, удалять, при этом имея аналогичный класс в оболочке, будто бы наш код был написан на Java. Задача эта не слишком сложная, но прежде чем опытные прогеры закрыли эту статью, я оговорюсь, что в следующей части мы уже будем работать с каллбэками - вызовами Java листенеров из нашего С++ кода, а вот это уже задача совсем нетривиальная, требующая понимания работы JNI и Dalvik. Но обо всем по порядку. Итак, у нас есть некий CPP класс и Java оболочка. Через JNI мы можем вызывать только С-функции, то есть не объектный код. Так как же нам работать с ООП? Главная проблема - не столько вызовы, сколько хранение адреса объекта нативного класса. Лично для себя я нашел решение - хранить его в Java классе, как long. То есть, у нас получается приблизительно такой код:
-
Getting GPS coordinates from Android through Go wasn't easy, but it's done. It's straightforward when you get the JNI weirdness, but it's a lot of boilerplate and hard to debug.
I'll try to integrate directly it into Fyne with a nice API in the future.
-
Getting GPS coordinates from Android through Go wasn't easy, but it's done. It's straightforward when you get the JNI weirdness, but it's a lot of boilerplate and hard to debug.
I'll try to integrate directly it into Fyne with a nice API in the future.
-
Getting GPS coordinates from Android through Go wasn't easy, but it's done. It's straightforward when you get the JNI weirdness, but it's a lot of boilerplate and hard to debug.
I'll try to integrate directly it into Fyne with a nice API in the future.
-
Getting GPS coordinates from Android through Go wasn't easy, but it's done. It's straightforward when you get the JNI weirdness, but it's a lot of boilerplate and hard to debug.
I'll try to integrate directly it into Fyne with a nice API in the future.
-
Getting GPS coordinates from Android through Go wasn't easy, but it's done. It's straightforward when you get the JNI weirdness, but it's a lot of boilerplate and hard to debug.
I'll try to integrate directly it into Fyne with a nice API in the future.
-
#Android friends, how do you unit test your #JNI / #KNI code? Do you write extra KNI glue just so you can trigger internal native methods that call back out into #Kotlin?
Do you restrict yourself to only integration tests and black-box tests and just *not* unit-test this stuff?
All solutions we’ve tried/considered so far kinda feel bad.
(I'm mostly dealing with C/C++ and Kotlin)
-
Learn about improved tools, performance, diagnostics and other hidden gems in new #Java #LTS in my new article in Java aktuell (german)
#jfr #jpackage #ZGC #Shenandoah #JNI #AppCDS #Monitoring #JNI #ForeignMemory
https://www.doag.org/fileadmin/Daten/Zeitschriften/Java_aktuell/2022/05-2022-Java_aktuell-WEB.pdf#page=10