美文网首页
golang C 混编

golang C 混编

作者: wyrover | 来源:发表于2018-06-22 21:37 被阅读61次

    简单例子

    cGo.go

    package main
    
    //#include <stdio.h>
    //void callC() {
    //    printf("Calling C code!\n");
    //}
    import "C"
    import "fmt"
    
    func main() {
        fmt.Println("A Go statement!")
        C.callC()
        fmt.Println("Another Go statement!")
    }
    
    

    稍复杂例子

    callC.h

    #ifndef CALLC_H
    #define CALLC_H
    
    void cHello();
    void printMessage(char* message);
    
    #endif
    

    callC.c

    #include <stdio.h>
    #include "callC.h"
    
    void cHello() {
        printf("Hello from C!\n");
    }
    
    void printMessage(char* message) {
        printf("Go send me %s\n", message);
    }
    

    callC.go

    package main
    
    // #cgo CFLAGS: -I${SRCDIR}/callClib
    // #cgo LDFLAGS: ${SRCDIR}/callC.a
    // #include <stdlib.h>
    // #include <callC.h>
    import "C"
    
    import (
        "fmt"
        "unsafe"
    )
    
    func main() {
        fmt.Println("Going to call a C function!")
        C.cHello()
    
        fmt.Println("Going to call another C function!")
        myMessage := C.CString("This is Mihalis!")
        defer C.free(unsafe.Pointer(myMessage))
        C.printMessage(myMessage)
    
        fmt.Println("All perfectly done!")
    }
    
    

    相关文章

      网友评论

          本文标题:golang C 混编

          本文链接:https://www.haomeiwen.com/subject/giylyftx.html