示例工程 25-c-interop

25-c-interop/Tests/Ch25KitTests/CInteropTests.swift

swift · 1.3 KB

import Testing
 
@testable import Ch25Kit
 
@Suite("C 调用")
struct CInteropTests {
    @Test func addUsesCImplementation() {
        #expect(CInterop.add(20, 22) == 42)
        #expect(CInterop.add(-5, 5) == 0)
    }
 
    @Test func stringLengthCountsUTF8Bytes() {
        #expect(CInterop.byteLength("abc") == 3)
        #expect(CInterop.byteLength("你好") == 6)
        #expect(CInterop.byteLength("") == 0)
    }
 
    @Test func fillWritesThroughPointer() {
        #expect(CInterop.filled(count: 4, value: 7) == [7, 7, 7, 7])
        #expect(CInterop.filled(count: 0, value: 1).isEmpty)
    }
 
    @Test func structRoundTrip() {
        let point = CInterop.makePoint(x: 3, y: 4)
        #expect(point.x == 3)
        #expect(point.y == 4)
        #expect(CInterop.sum(point) == 7)
    }
 
    @Test func cStructLayoutMatchesSwift() {
        #expect(MemoryLayout<CPoint>.size == 8)
        #expect(MemoryLayout<CPoint>.stride == 8)
        #expect(MemoryLayout<CPoint>.alignment == 4)
    }
}
 
@Suite("回调与导出")
struct CallbackTests {
    @Test func conventionCClosureWorks() {
        #expect(CInterop.callDouble(21) == 42)
        #expect(CInterop.callDouble(0) == 0)
    }
 
    @Test func cdeclFunctionIsCallable() {
        #expect(ExportedFunction.callTriple(14) == 42)
    }
}