0Pricing
Kotlin Multiplatform Academy · Aula

Interoperação com bibliotecas C

Associe uma dependência C para usá-la no código compartilhado.

Interoperação com bibliotecas C é uma aula grátis de Kotlin Multiplatform Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Kotlin Multiplatform Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Kotlin Multiplatform Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Reaching Into C

Sometimes the code you need is a plain C library. Kotlin/Native can call it directly through a tool called cinterop. 🔌

What cinterop Produces

cinterop reads C headers and generates Kotlin bindings. After that, the C functions and types look like ordinary Kotlin declarations you can call.

The .def File

You describe the library in a small def file: which headers to read and which library to link. This is the recipe cinterop follows.

headers = mylib.h
package = mylib

Wire It Into Gradle

Inside the kotlin block you register a cinterop entry for your target. Gradle then runs the tool and adds the generated bindings to compilation.

cinterops.create("mylib")

Calling a C Function

Once generated, a C function is just a Kotlin function. Import it from your def package and call it like any other shared function.

import mylib.compute
val r = compute(21)

C Pointers Become CPointer

A raw C pointer maps to Kotlin CPointer. It is typed, so the compiler knows what it points at instead of leaving you with a bare address.

Memory You Must Manage

C does not free things for you. Allocate inside a memScoped block so Kotlin releases the native memory automatically when the block ends.

memScoped {
  val buf = allocArray<ByteVar>(16)
}

Strings Cross the Line

Use helpers to convert between Kotlin and C strings. A Kotlin String becomes a C buffer with cstr, and you convert back when reading results.

Opaque Types and Structs

C structs map to Kotlin classes with field access. An opaque type you never inspect is just a pointer you pass straight back to the library.

Keep It on Native Targets

cinterop bindings exist only for Kotlin/Native targets like iOS. Wrap the calls behind expect/actual so commonMain stays platform-free.

Wrap, Then Expose

Hide pointers and memScoped behind a friendly Kotlin API. Callers get clean types and never touch raw C details directly.

Quick Check

A quick check on managing C memory from Kotlin.

Recap: cinterop

You saw that a def file plus Gradle generates Kotlin bindings for a C library, pointers map to CPointer, and memScoped manages native memory. 🎉

Perguntas Frequentes

A aula “Interoperação com bibliotecas C” é grátis?

Sim — o texto completo de “Interoperação com bibliotecas C” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Kotlin Multiplatform Academy, atualize para CoddyKit PRO. O curso de Kotlin Multiplatform Academy inclui 4 aulas no total.

O que vou aprender em “Interoperação com bibliotecas C”?

Associe uma dependência C para usá-la no código compartilhado. Você pratica Kotlin Multiplatform Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Kotlin Multiplatform Academy?

Nenhuma experiência prévia é necessária. Kotlin Multiplatform Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.

Quanto tempo leva a aula “Interoperação com bibliotecas C”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Kotlin Multiplatform Academy?

Sim. Cada aula de Kotlin Multiplatform Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Use frameworks da Apple a partir do Kotlin
  2. Memória e ARC no Kotlin/Native
  3. Interoperação com bibliotecas C
  4. Envolva um SDK nativo de forma limpa
← Voltar para Kotlin Multiplatform Academy