0Pricing
Kotlin Multiplatform Academy · Lección

cinterop con bibliotecas de C

Vincule una dependencia de C para usarla en código compartido.

cinterop con bibliotecas de C es una lección gratuita de Kotlin Multiplatform Academy en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Kotlin Multiplatform Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Kotlin Multiplatform Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en 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. 🎉

Preguntas frecuentes

¿La lección «cinterop con bibliotecas de C» es gratis?

Sí — el texto completo de «cinterop con bibliotecas de C» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Kotlin Multiplatform Academy, actualiza a CoddyKit PRO. El curso de Kotlin Multiplatform Academy incluye 4 lecciones en total.

¿Qué aprenderé en «cinterop con bibliotecas de C»?

Vincule una dependencia de C para usarla en código compartido. Practicas Kotlin Multiplatform Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Kotlin Multiplatform Academy?

No se requiere experiencia previa. Kotlin Multiplatform Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.

¿Cuánto tiempo toma la lección «cinterop con bibliotecas de C»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Kotlin Multiplatform Academy?

Sí. Cada lección de Kotlin Multiplatform Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Utilice frameworks de Apple desde Kotlin
  2. Memoria y ARC en Kotlin/Native
  3. cinterop con bibliotecas de C
  4. Envuelva limpiamente un SDK nativo
← Volver a Kotlin Multiplatform Academy