简单例子
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!")
}
有疑问加站长微信联系(非本文作者)