Golang创建DLL

  • 示例代码
package main // 这个文件一定要在main包下面

import "C" // 这个 import 也是必须的,有了这个才能生成 .h 文件

// 下面这一行不是注释,是导出为SO库的标准写法,注意 export前面不能有空格!!!
// 若没有此句,则不会生成对应的头文件(.h)

//export hello
func hello(value string)*C.char { // 如果函数有返回值,则要将返回值转换为C语言对应的类型
    return C.CString("hello" + value)
}

func main(){
    // 此处一定要有main函数,有main函数才能让cgo编译器去把包编译成C的库
    // main函数并不会调用
}
  • 编译生成dll
$ go build -buildmode=c-shared -o hello.dll hello.go
  • 生成对应的头文件
/* Code generated by cmd/cgo; DO NOT EDIT. */

/* package command-line-arguments */


#line 1 "cgo-builtin-export-prolog"

#include <stddef.h> /* for ptrdiff_t below */

#ifndef GO_CGO_EXPORT_PROLOGUE_H
#define GO_CGO_EXPORT_PROLOGUE_H

#ifndef GO_CGO_GOSTRING_TYPEDEF
typedef struct { const char *p; ptrdiff_t n; } _GoString_;
#endif

#endif

/* Start of preamble from import "C" comments.  */

/* End of preamble from import "C" comments.  */

/* Start of boilerplate cgo prologue.  */
#line 1 "cgo-gcc-export-header-prolog"

#ifndef GO_CGO_PROLOGUE_H
#define GO_CGO_PROLOGUE_H

typedef signed char GoInt8;
typedef unsigned char GoUint8;
typedef short GoInt16;
typedef unsigned short GoUint16;
typedef int GoInt32;
typedef unsigned int GoUint32;
typedef long long GoInt64;
typedef unsigned long long GoUint64;
typedef GoInt64 GoInt;
typedef GoUint64 GoUint;
typedef __SIZE_TYPE__ GoUintptr;
typedef float GoFloat32;
typedef double GoFloat64;
typedef float _Complex GoComplex64;
typedef double _Complex GoComplex128;

/*
  static assertion to make sure the file is being used on architecture
  at least with matching size of GoInt.
*/
typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1];

#ifndef GO_CGO_GOSTRING_TYPEDEF
typedef _GoString_ GoString;
#endif
typedef void *GoMap;
typedef void *GoChan;
typedef struct { void *t; void *v; } GoInterface;
typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;

#endif

/* End of boilerplate cgo prologue.  */

#ifdef __cplusplus
extern "C" {
#endif


extern char* hello(GoString p0);

#ifdef __cplusplus
}
#endif
  • Qt调用DLL测试
    程序结构
# 项目配置
QT += widgets

INCLUDEPATH += $$PWD/include
LIBS += -L$$PWD/bin -lhello

SOURCES += \
    main.cpp
// 测试代码
#include "hello.h"
#include <QApplication>
#include <QDebug>
#include <algorithm>

using std::begin;
using std::end;

int main( int argc, char *argv[] ) {
    QApplication app( argc, argv );

    char arr[] = " World";
    GoString str{ arr, end( arr ) - begin( arr ) };
    
    qDebug() << hello( str );

    return 0;
}

输出结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值