Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

《Mastering Go》 读书笔记 #2

Open
bonfy opened this issue Nov 11, 2020 · 2 comments
Open

《Mastering Go》 读书笔记 #2

bonfy opened this issue Nov 11, 2020 · 2 comments
Labels
note 笔记

Comments

@bonfy
Copy link
Owner

bonfy commented Nov 11, 2020

书籍链接: https://www.amazon.com/Mastering-production-applications-concurrency-structures-ebook/dp/B07WC24RTQ
Code: https://github.com/PacktPublishing/Mastering-Go

@bonfy
Copy link
Owner Author

bonfy commented Nov 11, 2020

调用C程序

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!")
}

@bonfy bonfy added the note 笔记 label Nov 11, 2020
@bonfy
Copy link
Owner Author

bonfy commented Nov 11, 2020

复杂点的 调用 C

callClib/callC.h

#ifndef CALLC_H
#define CALLC_H

void cHello();
void printMessage(char* message);

#endif

callClib/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!")
}
$ gcc -c callClib/*.c  
# 当前目录会产生 callC.o

$ ar rs callC.a *.o
# 产生 callC.a
$ file callC.a
callC.a: current ar archive random library

$ rm callC.o

$ go build callC.go
# 产生 可执行 的 callC.exe
$ .\callC.exe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
note 笔记
Projects
None yet
Development

No branches or pull requests

1 participant