golang cgo调用lib

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

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 wind.kaisa@gmail.com

文章标题:golang cgo调用lib

本文作者:kaisawind

发布时间:2019-11-19, 06:16:59

最后更新:2020-12-04, 10:18:58

原始链接:https://kaisawind.gitee.io/2019/11/18/2019-11-19-cgo-lib/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏