GO 代码调用C 函数举例2

测试环境:Linux

第一部分:C代码

(1)头文件 person.h

#ifndef PERSON_H
#define PERSON_H

typedef struct APerson  {
    const char * name;
    const char * long_name;
} APerson ;

APerson *get_person(const char * name, const char * long_name);

#endif /* !PERSON_H */

(2)源文件 person.c
#include <stdlib.h>
#include "person.h"


APerson *get_person(const char *name, const char *long_name){

    APerson *fmt = malloc(sizeof(APerson));
    fmt->name = name;
    fmt->long_name = long_name;

    return fmt;
};

(3)编译成共享库文件

gcc -o libperson.so -Wall -g -shared -fPIC person.c

第二部分:go 代码

(1) main.go

package main

/*
#cgo CFLAGS: -g -Wall
#cgo LDFLAGS: -L. -lperson
#include "person.h"
*/
import "C"
import (
    "fmt"
)

type (
    Person C.struct_APerson
)

func (p *Person) Name() string {
    return C.GoString(p.name)
}

func (p *Person) LongName() string {
    return C.GoString(p.long_name)
}


func GetPerson(name string, long_name string) *Person {
    return (*Person)(C.get_person(C.CString(name), C.CString(long_name)))
}


func main(){
    var f *Person
    f = GetPerson("tim", "tim hughes")
    fmt.Printf("Hello Go world: My name is %s, %s.\n", C.GoString(f.name), C.GoString(f.long_name))

    fmt.Printf("Hello Go world: My name is %s, %s.\n", f.Name(), f.LongName())
}

(2) 编译生成可执行文件

go build main.go

(3) 运行及结果:

$export LD_LIBRARY_PATH=./:$LD_LIBRARY_PATH

$./main
Hello Go world: My name is tim, tim hughes.
Hello Go world: My name is tim, tim hughes.

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值