01Requirements준비물
- A JDK for Gradle, and Git.Gradle 용 JDK 와 Git.
- The Android SDK (with
ANDROID_HOMEset) for Android targets.Android 타깃에는 Android SDK (ANDROID_HOME설정). - macOS with Xcode for iOS targets.iOS 타깃에는 Xcode 가 있는 macOS.
You do not install Python: Gradle downloads the CPython build for each platform, verifies it, and extracts it. The version is set by pythonVersion in gradle.properties.Python 을 설치하지 않는다. Gradle 이 플랫폼마다 CPython 빌드를 내려받아 검증하고 푼다. 버전은 gradle.properties 의 pythonVersion 으로 정한다.
02Clone and run클론하고 실행하기
git clone https://github.com/thisisthepy/python-multiplatform
cd python-multiplatform
./gradlew :sample:run
The desktop sample starts CPython, publishes a Kotlin-built list into Python, evaluates an expression, and drives a Kotlin class from Python.데스크톱 샘플은 CPython 을 시작하고, Kotlin 에서 만든 리스트를 Python 에 게시하고, 식을 평가하고, Python 에서 Kotlin 클래스를 움직인다.
03Your first call첫 호출
import python.multiplatform.ffi.PyObject
import python.multiplatform.ffi.Python3
import python.multiplatform.ffi.types.basic.PyInt
import python.multiplatform.ffi.types.collections.PyList
fun main() {
Python3.initialize()
val numbers = PyList.fromList(listOf(2L, 3L, 5L, 7L, 11L).map { PyInt.from(it) })
Python3.import("__main__").setAttr("kotlin_numbers", numbers)
val globals = Python3.import("__main__").dict
val result: PyObject = Python3.eval("sum(kotlin_numbers) * 2", 258, globals, globals)
println("${result.Type.name}: $result") // int: 56
}
There is no close() in that code, and none is missing: every wrapper releases its Python reference when the Kotlin object is collected.위 코드에는 close() 가 없고, 빠진 것도 아니다. 모든 래퍼는 Kotlin 객체가 수거될 때 Python 참조를 놓는다.
04Use it from Maven CentralMaven Central 에서 쓰기
Consumers must build with Kotlin 2.4.20-Beta2, the version the artifacts are compiled with. A desktop app that Python calls back into:소비자는 아티팩트가 컴파일된 Kotlin 2.4.20-Beta2 로 빌드해야 한다. Python 이 다시 호출하는 데스크톱 앱:
// settings.gradle.kts
pluginManagement { repositories { mavenCentral(); gradlePluginPortal() } }
dependencyResolutionManagement { repositories { mavenCentral(); google() } }
// build.gradle.kts of a Kotlin Multiplatform app
plugins {
kotlin("multiplatform") version "2.4.20-Beta2"
id("org.thisisthepy.python.multiplatform.bindings") version "3.15.0-alpha03"
}
kotlin {
jvm("desktop") {
@OptIn(org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi::class)
binaries { executable { mainClass.set("app.MainKt") } }
}
sourceSets.commonMain.dependencies {
implementation("org.thisisthepy:python-multiplatform:3.15.0-alpha03")
// Compose hosts (PythonAppView, PythonWidget, PythonLauncher):
// implementation("org.thisisthepy:python-multiplatform-compose:3.15.0-alpha03")
}
}
// A KMP executable is otherwise treated as a library and gets no FunctionTable.
pythonBindings { role.set("app") }
// src/desktopMain/kotlin/app/Main.kt
package app
import python.multiplatform.ffi.Python3
import python.multiplatform.ffi.upcall.PythonProxySource
import python.native.ffi.UpcallStub
class Greeter(val subject: String) {
fun greet(times: Long): String = List(times.toInt()) { "hello $subject" }.joinToString(", ")
}
fun main() {
Python3.initialize()
// Upcalls: install the generated table, bind the entry points, install the proxies.
python.multiplatform.generated.FunctionTable.installInto()
Python3.exec(
"""
import ctypes
_pm_resolve = ctypes.CFUNCTYPE(ctypes.c_long, ctypes.c_char_p)(${UpcallStub.resolveHandleStubAddr})
_pm_invoke = ctypes.CFUNCTYPE(ctypes.py_object, ctypes.c_long, ctypes.py_object)(${UpcallStub.invokeWithArgsStubAddr})
_pm_release = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_long)(${UpcallStub.releaseObjectStubAddr})
_pm_cancel = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_long)(${UpcallStub.cancelCallStubAddr})
""".trimIndent(),
)
PythonProxySource.install()
Python3.exec("from app import Greeter\nprint(Greeter('Kotlin').greet(2), flush=True)")
}
The library, the KSP processor, the Compose host and the Gradle plugin share one version, $pythonVersion-$libraryVersionSuffix, and are published together on Maven Central; the current release is 3.15.0-alpha03. google() is needed for Android targets.라이브러리, KSP 프로세서, Compose 호스트, Gradle 플러그인은 $pythonVersion-$libraryVersionSuffix 라는 한 버전을 쓰고 Maven Central 에 함께 올라간다. 현재 릴리스는 3.15.0-alpha03 이다. Android 타깃에는 google() 이 필요하다.
05Verify a change변경 검증하기
./gradlew :python-multiplatform:compileKotlinAndroidNativeArm64 --console=plain > .cache/build.log 2>&1; echo "EXIT=$?"
./gradlew :python-multiplatform:desktopTest --rerun --console=plain > .cache/test.log 2>&1; echo "EXIT=$?"
./gradlew :python-multiplatform-ksp:fixtures:app:desktopTest --rerun
./gradlew :python-multiplatform-compose:fixtures:compose:desktopTest --rerun
./gradlew :python-multiplatform-gradle-plugin-fixtures:artifact:desktopTest --rerun
Run the fixture modules one by one: a single invocation has hidden an ordering dependency before. Read exit codes from a file, never through a pipe.픽스처 모듈은 하나씩 따로 돌린다. 한 번에 돌리면 순서 의존성이 가려진 적이 있다. 종료 코드는 파이프가 아니라 파일에서 읽는다.