InteropExample: port to new interop

This commit is contained in:
Svyatoslav Scherbina
2016-11-22 13:18:49 +07:00
parent 8a486d7fae
commit c5f00c3301
+14 -17
View File
@@ -1,13 +1,12 @@
import kotlin_native.interop.*
import kotlin_.cinterop.*
import llvm.*
fun main(args: Array<String>) {
fun main(args: Array<String>) = memScoped {
val module = LLVMModuleCreateWithName("module")
println("module=" + module.getNativePtr().asLong())
println("module=" + module.rawValue)
val paramTypes = mallocNativeArrayOf(LLVMOpaqueType, LLVMInt32Type(), LLVMInt32Type())
val retType = LLVMFunctionType(LLVMInt32Type(), paramTypes[0], 2, 0)
free(paramTypes)
val paramTypes = allocArrayOf(LLVMInt32Type(), LLVMInt32Type())
val retType = LLVMFunctionType(LLVMInt32Type(), paramTypes[0].ptr, 2, 0)
val sum = LLVMAddFunction(module, "sum", retType)
val entry = LLVMAppendBasicBlock(sum, "entry")
@@ -15,34 +14,32 @@ fun main(args: Array<String>) {
LLVMPositionBuilderAtEnd(builder, entry)
val tmp = LLVMBuildAdd(builder, LLVMGetParam(sum, 0), LLVMGetParam(sum, 1), "tmp")
LLVMBuildRet(builder, tmp)
val engineRef = malloc(Ref to LLVMOpaqueExecutionEngine)
val errorRef = malloc(Ref to Int8Box)
val engineRef = alloc<LLVMExecutionEngineRefVar>()
val errorRef = allocPointerTo<CInt8Var>()
LLVMInitializeNativeTarget()
errorRef.value = null
if (LLVMCreateExecutionEngineForModule(engineRef, module, errorRef) != 0) {
if (LLVMCreateExecutionEngineForModule(engineRef.ptr, module, errorRef.ptr) != 0) {
println("failed to create execution engine")
return
}
val error = errorRef.value
if (error != null) {
println(CString.fromArray(NativeArray.byRefToFirstElem(error, Int8Box)).toString())
println(error.asCString().toString())
return
}
println(LLVMGetTypeKind(LLVMInt32Type()))
val x = 5L
val y = 6L
val args = malloc(array[2](Ref to LLVMOpaqueGenericValue))
args[0].value = LLVMCreateGenericValueOfInt(LLVMInt32Type(), x, 0)
args[1].value = LLVMCreateGenericValueOfInt(LLVMInt32Type(), y, 0)
val runRes = LLVMRunFunction(engineRef.value, sum, 2, args[0])
val args = allocArrayOf(
LLVMCreateGenericValueOfInt(LLVMInt32Type(), x, 0),
LLVMCreateGenericValueOfInt(LLVMInt32Type(), y, 0))
val runRes = LLVMRunFunction(engineRef.value, sum, 2, args[0].ptr)
println(LLVMGenericValueToInt(runRes, 0))
if (LLVMWriteBitcodeToFile(module, "/tmp/sum.bc") != 0) {
println("error writing bitcode to file, skipping")
}
LLVMDisposeBuilder(builder)
LLVMDisposeExecutionEngine(engineRef.value)
}