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

💰

×

Help us with donation