kaisawind's blog
  • 关于
  • 所有帖子

golang cgo调用lib - Tue, Nov 19, 2019

golang cgo调用lib

hello.h

#ifndef HELLO_H_
#define HELLO_H_

#ifdef __cplusplus
extern "C" {
#endif

extern int hello(char *name, int age);

#ifdef __cplusplus
}
#endif

#endif // HELLO_H_

hello.cpp

#include <stdio.h>
#include "hello.h"

int hello(char *name, int age) {
    printf("Hello %s, your age is %d.\n", name, age);
    return age;
}

hello.a

gcc -Wall -c hello.c
ar -rv libhello.a hello.o

hello.go

package main

/*
#cgo CFLAGS: -I.
#cgo LDFLAGS: -L. -lhello
#include <stdio.h>
#include <stdlib.h>
#include "hello.h"
*/
import "C"
import (
	"fmt"
	"unsafe"
)

func main() {
	name := C.CString("Jack")
	defer C.free(unsafe.Pointer(name))
	age := C.int(18)

	result := C.hello(name, age)
	fmt.Println(result)
}

output

GOROOT=C:\Go #gosetup
GOPATH=E:\kaisawind\go #gosetup
C:\Go\bin\go.exe build -o C:\Users\kaisa\AppData\Local\Temp\___go_build_github_com_kaisawind_ffmpeg_go_test.exe github.com/kaisawind/ffmpeg.go/test #gosetup
C:\Users\kaisa\AppData\Local\Temp\___go_build_github_com_kaisawind_ffmpeg_go_test.exe #gosetup
18
Hello Jack, your age is 18.

Process finished with exit code 0


辽ICP备2021007608号 | © 2025 | kaisawind

Facebook Twitter GitHub

▄