golang C 混编

简单例子

cGo.go

package main

//#include 
//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 
#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 
// #include 
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 混编)