Swift Data to CPP std::vector

I am trying to create a CPP library to be used in my Swift application. The CPP code in this library will later be used in a Kotlin based Android app as well.

I am trying to create a function in CPP which gets an std::vector<uint_8_t> as a parameter. This is the function header:

std::vector<std::vector<u_int8_t>> CxxCustomEncoder::createDataChunks(const std::vector<u_int8_t> originalData, size_t chunkSize).

By using Swift <-> CPP interoperability in Xcode 15, I can directly call this function from Swift code. I have tried something like this:

public static func createDataChunks(data: Data, chunkLength: Int) -> [Data] {
    var cxxEncoder = CxxCustomEncoder()
    let byteArray = data.map { UInt8($0) }
    let chunks = cxxEncoder.createDataChunks(byteArray, 1)
}

But it doesn't work. I get the error:
Cannot convert value of type '[UInt8]' to expected argument type 'std.__1.vector<CUnsignedChar, allocator<CUnsignedChar>>'

How can this be done? How to pass a Swift array to CPP function as std::vector<>?

1 Like