jni-zero
O que ela faz
Esta skill orienta sua IA no JNI Zero, uma ferramenta que gera código para chamadas entre Java e C++. Ela é indicada para desenvolvedores Android que escrevem essas pontes.
Quando usar
- ✓Quando você adiciona um alvo generate_jni ou um método @CalledByNative a código Android.
- ✓Quando você escreve código C++ que chama Java por meio de cabeçalhos JNI gerados.
- ✓Quando você precisa verificar como os cabeçalhos JNI gerados devem ser incluídos e usados.
Link da skill
https://github.com/chromium/chromium/blob/main/third_party/jni_zero/skills/jni-zero/SKILL.mdCopie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.
Como usar
O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.
Mensagem pronta para colar
Para Claude Code, Codex ou Cursor: rode na pasta do projeto e a skill fica instalada.
Baixe o SKILL.md e coloque na pasta de skills do seu agente.
Exemplo do que pedir para a IA
“Você pode adicionar uma ligação JNI Zero para que meu método Java possa chamar o código C++?”
5 skills novas por semana. 1 minuto de leitura.
Como funciona
A skill dá à IA as regras de build e de codificação do JNI Zero, como nomes, inclusão de cabeçalhos e tipos seguros. Em seguida, a IA as aplica aos arquivos Java e C++.
Conteúdo técnico (SKILL.md original)
Texto original do autor, em inglês, direto do GitHub.
JNI Zero Guidance
JNI Zero is a code generator that lives at //third_party/jni_zero. It's
written in Python and has both C++ and Java APIs. The main reference is in
//third_party/jni_zero/README.md.
Guidance for GN
- Use
_jnias a suffix for allgenerate_jni()andgenerate_jar_jni()targets. generate_jni()targets should be in the sameBUILD.gnas theandroid_library()that owns the sources.- Ensure that all
android_library()targets that have a.javafile that is listed in agenerate_jni()target also contain adepsentry onto thefoo_jni_javatarget.
Guidance for C++
Generated headers:
- Are generated at
{OUTPUT_DIR}/gen/jni_headers/{BUILD_GN_SUBDIR}/{TARGET_NAME}/{JavaClass}_jni.h - Omit the
gen/jni_headersprefix when #include'ing them. - #includes of
_jni.hheaders from.ccfiles should come after all other #includes and be preceded with the comment:// Must come after headers that provide symbols used by @JniType.
- #includes of
_jni.hheaders from.hfiles should always use the_shared_jni.hvariants.
API Usage:
- When returning or passing a null
JavaRef, usenullptrrather than calling a constructor. - Prefer type-safe
JArray<JFoo>overjobjectArray/JArray<jobject>, as well as for other array types (JArray<T>overjTArray). - Use the
jni_zero::namespace instead of thebase::android::aliases (e.g. for*JavaRef, andAttachBaseContext()) - To call static Java methods, do not call the
Java_Clazz_method()functions directly. Call them through their typed wrappers:ClazzJni::method() - To call constructors methods, use
ClazzJni::New() - To call member functions given a
JavaRef<jobject>, useJava_Clazz_method() - To call member functions given a
JavaRef<JFoo>, usefoo->method()
Creation and ownership of Java counterparts:
- A native object owns a Java class if it creates it via JNI.
- If a native object owns a Java object, ensure that its destructor sets the Java object's native pointer field to 0 from its destructor.
- Add a comment explaining the ownership and lifecycle of the class and its Java
counterpart.
- E.g.: "This class creates and owns its Java counterpart, and holds a strong JNI global reference to it. When this is destroyed, it must call clearNativePtr to prevent Java from calling back into destroyed memory."
Defining native entry point methods:
- Use the signatures from the examples within the generated
_jni.hfiles - Omit the
JNIEnv*parameter if it will be unused.
Guidance for Java
- Name all @NativeMethods interfaces "Natives", and make them package-private.
- Use
@JniType()on as many parameters and return types as possible. - Parameters and return types that may be
nullmust be annotated as@Nullableto avoid a runtime null-check. - A Java class owns a native object if it creates it via JNI.
- If a Java class owns a native object, ensure that there is an
onDestroy()method that callsdeletevia JNI, and sets the field0. - Add a comment explaining the ownership and lifecycle of the class and its C++
counterpart.
- E.g.: "This class is created and owned by its C++ counterpart. It holds a reference to it in the field mNativePtr, which the C++ counterpart must set to 0 when it is destroyed by calling clearNativePtr."
Guidance for @JniType
- Search all .h files for
FromJniTypeorToJniTypeto discover which types are currently supported. - Strings are either
std::stringorstd::u16string. - Although
std::optionalcan be used for@Nullabletypes, it always leads to larger binary size. Prefer empty containers and empty strings, and usestd::optionalonly when empty and null are semantically different.nullwill convert to an empty string or an empty container, so use@JniType("container or string") @Nullable List/Stringwhen applicable.
- Prefer to use
List<>over typed object arrays.
Converting From jobject to Correctly-Typed jobject Subclasses
Core Steps
1. Type Conversion
- Change
JavaRef<jobject>andScopedJavaLocalRef<jobject>to use generated classes that extendjobject. - E.g.,
JavaRef<jobject>for aFooBarclass becomesJavaRef<JFooBar>. - Special Cases:
java.lang.Objectmaps tojobjectjava.lang.Stringmaps tojstringjava.lang.Throwablemaps tojthrowablejava.lang.Classmaps tojclass
- Use
.As<JFoo>()to con
Perguntas frequentes
O que é JNI?
JNI é a ponte que permite ao código Java chamar código C++ no Android. É fácil errar quando escrito à mão.
Preciso de um sistema de build específico?
A orientação usa regras de build do GN, então ela se encaixa em projetos que compilam com GN.
Isto é só para o Chromium?
A skill se refere à cópia do JNI Zero do Chromium, então seus caminhos correspondem a essa configuração.
Detalhes
Descrição original do autor
Guidance for working with JNI Zero to call between C++ and Java.
repo: chromium/chromium
Popularidade
- Estrelas no GitHub
- 25 mil
- Posição no ranking
- #10065
- Licença
- BSD-3-Clause
- Atualizada em
- 02/11/2026
Comentários
- …
Mais skills deste repositório
fuzzing
25 milAjuda seu agente a escrever testes de fuzzing que alimentam o código com muitas entradas aleatórias para encontrar falhas e bugs em código C++.
gn-deps-debugging
25 milAjuda seu agente a corrigir erros de build causados por dependências ausentes ou incorretas em arquivos de build GN, sem adicionar dependências amplas e desnecessárias.
java-memory-leaks
25 milAjuda seu agente a encontrar e corrigir vazamentos de memória em Java em apps Android, lendo relatórios de vazamento do LeakCanary.
jni-type-conversion
25 milAjuda seu agente a substituir o código manual de conversão de Java para C++ por anotações @JniType mais simples em código Android.
Skills parecidas
android-clean-architecture
280 milFaz seu agente organizar projetos Android de forma eficiente. Ele estrutura o código para facilitar a manutenção e o desenvolvimento de novos recursos.
compose-multiplatform-patterns
280 milAjuda seu agente a usar Compose Multiplatform e Jetpack Compose em projetos KMP. Cobre estado, navegação, temas e performance.
dart-flutter-patterns
280 milFaz seu agente escrever código para apps Dart e Flutter. Ele usa padrões modernos para criar apps robustos e fáceis de gerenciar.