Search code examples
winapikotlincompiler-errorsnativekotlin-native

How to initialize LPBOOL? Win32 Api in Kotlin Native


How do I call this in Kotlin Native

    val result = CopyFileExA(
                          oldFile,
                          newFile,
                          null,
                          null,
                          false,
                          COPY_FILE_FAIL_IF_EXISTS
                         )

while false is not accepted as LPBOOL? How do I initialize LPBOOL to be used in Kotlin native interface?

I am getting the following error :

the boolean literal does not conform to the expected type

LPBOOL? /* = CPointer */>? */ false,


Solution

  • Answering the question that is already in github from @olonho

    You need to alloc a variable using the especial platform types NativePlacement

    import kotlinx.cinterop.*
    import platform.windows.*
    
    val buffer = nativeHeap.allocArray<ByteVar>(size)
    <use buffer>
    nativeHeap.free(buffer)
    

    but for avoid the free call or unallocated memory you can use the memScoped

    val fileSize = memScoped {
      val statBuf = alloc<statStruct>()
      val error = stat("/", statBuf.ptr)
      statBuf.st_size
    }
    

    important, the pointer binding will be with statBuf.ptr, then your code will be:

        memScoped {
          val oldFile = "README.md"
          val newFile = "${oldFile}.cp"
          val bool = alloc<BOOLVar>()
          bool.value = FALSE
    
          val result = CopyFileExA(
                  oldFile,
                  newFile,
                  null,
                  null,
                  bool.ptr,
                  COPY_FILE_FAIL_IF_EXISTS
          )
        }
    

    This have to be similar if you need to binding with a objective-c library.