golang代码

package main

import "C"

func main() {}

//export AddString
func AddString(a *C.char,b *C.char) *C.char {
    return C.CString(C.GoString(a)+C.GoString(b))
}

//export Hello
func Hello()  {
    println("hello")
}
  • 必须import "C"
  • c静态库需要导出的函数必须加上//export 函数名
  • 编译 go build -x -v -ldflags "-s -w" -buildmode=c-archive -o libtest.a
  • 编译成功后产生libaddstrings.h和libaddstrings.a
到此我们的c静态库就已经编译成功下来我们将静态库导入swift项目中

方式一

拷贝libaddstrings.h和libaddstrings.a到项目目录 点击Target -> Build Settings -> 搜索“Objective-C Bridging Header” -> 输入刚刚创建的头文件libaddstrings.h路径
import Foundation

var a1 = "aaa"

var a11 = a1.cString(using: .utf8)!

var sourceMutablePointer:UnsafeMutablePointer = UnsafeMutablePointer(&a11)!

var ss = AddString(sourceMutablePointer,sourceMutablePointer)!

Hello()

print(String(cString: ss))

方式二

拷贝libaddstrings.a,不用拷贝libaddstrings.h头文件,用silgen_name去调用c静态库中的函数
import Foundation

@_silgen_name("AddString")
func MyAddString(a:UnsafeMutablePointer<Int8>,b:UnsafeMutablePointer<Int8>) -> UnsafeMutablePointer<Int8>
@_silgen_name("Hello")

func Myhello()
var a1 = "aaa"
var a11 = a1.cString(using: .utf8)!
var sourceMutablePointer:UnsafeMutablePointer = UnsafeMutablePointer(&a11)!
var ss = MyAddString(a: sourceMutablePointer, b: sourceMutablePointer)
Myhello()
print(String(cString: ss))