《C/C++調用Golang 一》簡單介紹了C/C++調用Golang的方法步驟,只涉及一個簡單的函數調用。本文總結具體項目中的使用場景,將介紹三種較複雜的調用方式:一,C++向golang傳入複雜結構體;二,C++向golang傳入回調函數,在golang中調用C++函數;三,C++調用golang函數,返回複雜的結構體。git
(本文後面涉及三個例子,省略了編譯步驟,僅展現關鍵代碼。具體操做步驟參考《C/C++調用Golang 一》)github
採用avro來序列化與反序列化結構體。C++版avro使用官方版本,golang版avro使用gopkg.in/alanctgardner/gogen-avro.v4 。(C++代碼省略了avro結構體的序列化與反序列化,僅展現C++與Golang的交互部分)golang
package mainapp
import "C"函數
import "fmt"google
//export WriteDataspa
func WriteData(data []byte) int {blog
fmt.Println("WriteData ", data, len(data))內存
return 0get
}
func main() {
}
編譯生成的頭文件
/* Created by "go tool cgo" - DO NOT EDIT. */
/* package c_references_to_go/sample1 */
/* 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 GoInt32 GoInt;
typedef GoUint32 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_32_bit_pointer_matching_GoInt[sizeof(void*)==32/8 ? 1:-1];
typedef struct { const char *p; GoInt n; } GoString;
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 GoInt WriteData(GoSlice p0);
#ifdef __cplusplus
}
#endif
#include <Windows.h>
#include <stdio.h>
#include "sample1.h"
//#include "LargeStruct.h"
typedef GoInt (*funcPtrWriteData)(GoSlice p0);
int main(){
HMODULE h = LoadLibraryA("sample1.dll");
if (NULL == h || INVALID_HANDLE_VALUE == h)
{
return -1;
}
funcPtrWriteData pfWriteData = (funcPtrWriteData)GetProcAddress(h,"WriteData");
if (pfWriteData)
{
/* LargeStruct ls;
ls.ID = "100001";
ls.Name = "Peter";
Pet pet;
pet.Type = "Dog";
pet.Name = "WangCai";
pet.Age = 5;
ls.Pets.push_back(pet);*/
GoSlice p0;
p0.data = 0; //serial ls to binary
p0.len = p0.cap = 0; //binary len
pfWriteData(p0);
}
FreeLibrary(h);
return 0;
}
設置回調須要中間的橋接函數 CReportData
package main
import (
"fmt"
)
/*
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef int (*ptfFuncReportData)(const char* data,int len);
extern int CReportData(ptfFuncReportData pf,const char* data,int len);
*/
import "C"
import (
"bytes"
"c_references_to_go/sample3/avro_struct"
"unsafe"
)
var callBackFunc C.ptfFuncReportData
//export SetCallBack
func SetCallBack(f C.ptfFuncReportData) {
callBackFunc = f
}
//export BeginWork
func BeginWork() {
go func() {
for index := 0; index < 10; index++ {
var ls avro_struct.LargeStruct
ls.ID = fmt.Sprintf("ID%d", 1000+index)
ls.Name = fmt.Sprintf("Peter%d", index)
ls.Pets = []*avro_struct.Pet{&avro_struct.Pet{Type: "Dog", Name: "WangCai", Age: 5}}
var buf bytes.Buffer
ls.Serialize(&buf)
dataSlice := buf.Bytes()
GoReportData(dataSlice)
}
}()
}
func GoReportData(data []byte) {
C.CReportData(callBackFunc, (*C.char)(unsafe.Pointer(&data[0])), C.int(len(data)))
}
func main() {
}
bridge.c
#include "_cgo_export.h"
int CReportData(ptfFuncReportData pf,const char* data,int len){
return pf(data,len);
}
編譯後產生的頭文件
/* Created by "go tool cgo" - DO NOT EDIT. */
/* package c_references_to_go/sample2 */
/* Start of preamble from import "C" comments. */
#line 7 "Y:\\mygo\\src\\c_references_to_go\\sample2\\main.go"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef int (*ptfFuncReportData)(const char* data,int len);
extern int CReportData(ptfFuncReportData pf,const char* data,int len);
#line 1 "cgo-generated-wrapper"
/* 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 GoInt32 GoInt;
typedef GoUint32 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_32_bit_pointer_matching_GoInt[sizeof(void*)==32/8 ? 1:-1];
typedef struct { const char *p; GoInt n; } GoString;
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 void SetCallBack(ptfFuncReportData p0);
extern void BeginWork();
#ifdef __cplusplus
}
#endif
#include <Windows.h>
#include <stdio.h>
#include "sample2.h"
typedef void (*funcPtrSetCallBack)(ptfFuncReportData p0);
typedef void (*funcPtrBeginWork)();
int OnReportData(const char* data,int len){
printf("OnReportData %x %d\r\n",data,len);
return 0;
}
int main(){
HMODULE h = LoadLibraryA("sample2.dll");
if (NULL == h || INVALID_HANDLE_VALUE == h)
{
return -1;
}
funcPtrSetCallBack pfSetCallBack = (funcPtrSetCallBack)GetProcAddress(h,"SetCallBack");
funcPtrBeginWork pfBeginWork = (funcPtrBeginWork)GetProcAddress(h,"BeginWork");
if (pfSetCallBack)
{
pfSetCallBack(OnReportData);
}
if (pfBeginWork)
{
pfBeginWork();
}
Sleep(1000*10);
FreeLibrary(h);
return 0;
}
運行以後的輸出:
不能向C++程序返回Go slice、Go struct。(詳情見master分支 src/cmd/cgo/doc.go ,參考5)
package main
import (
"bytes"
"unsafe"
)
/*
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct {
char* Data;
int DataLen;
} GetLargeStruct_return;
extern GetLargeStruct_return* CopyLargeSturct(char* data,int dataLen);
extern void FreeLargeSturct(GetLargeStruct_return* ptr);
*/
import "C"
import (
"c_references_to_go/sample3/avro_struct"
)
//export GetLargeStruct
func GetLargeStruct(paraIn int) *C.GetLargeStruct_return {
var ls avro_struct.LargeStruct
ls.ID = "1000001"
ls.Name = "Peter"
ls.Pets = []*avro_struct.Pet{&avro_struct.Pet{Type: "Dog", Name: "WangCai", Age: 5}}
var buf bytes.Buffer
ls.Serialize(&buf)
dataSlice := buf.Bytes()
return C.CopyLargeSturct((*C.char)(unsafe.Pointer(&dataSlice[0])), C.int(len(dataSlice)))
}
//export FreeLargeStruct
func FreeLargeStruct(ptr *C.GetLargeStruct_return) {
C.FreeLargeSturct(ptr)
}
//export GetLargeStruct2
func GetLargeStruct2(paraIn int) (*C.char, int) {
var ls avro_struct.LargeStruct
ls.ID = "1000001"
ls.Name = "Peter"
ls.Pets = []*avro_struct.Pet{&avro_struct.Pet{Type: "Dog", Name: "WangCai", Age: 5}}
var buf bytes.Buffer
ls.Serialize(&buf)
dataSlice := buf.Bytes()
return (*C.char)(unsafe.Pointer(C.CBytes(dataSlice))), len(dataSlice)
}
//export FreeCBytes
func FreeCBytes(ptr *C.char) {
C.free(unsafe.Pointer(ptr))
}
func main() {
}
C函數源碼文件 (釋放C分配的內存)
#include "_cgo_export.h"
GetLargeStruct_return* CopyLargeSturct(char* data,int dataLen){
GetLargeStruct_return* result = (GetLargeStruct_return*)malloc(sizeof(GetLargeStruct_return));
result->DataLen = dataLen;
result->Data = 0;
if(dataLen>0){
result->Data = malloc(dataLen);
memcpy(result->Data,data,dataLen);
}
return result;
}
void FreeLargeSturct(GetLargeStruct_return* ptr){
if(ptr != 0){
if(ptr->Data != 0 ){
free(ptr->Data);
}
free(ptr);
}
}
編譯後產生的頭文件
/* Created by "go tool cgo" - DO NOT EDIT. */
/* package c_references_to_go/sample3 */
/* Start of preamble from import "C" comments. */
#line 8 "Y:\\mygo\\src\\c_references_to_go\\sample3\\main.go"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct {
char* Data;
int DataLen;
} GetLargeStruct_return;
extern GetLargeStruct_return* CopyLargeSturct(char* data,int dataLen);
extern void FreeLargeSturct(GetLargeStruct_return* ptr);
#line 1 "cgo-generated-wrapper"
/* 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 GoInt32 GoInt;
typedef GoUint32 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_32_bit_pointer_matching_GoInt[sizeof(void*)==32/8 ? 1:-1];
typedef struct { const char *p; GoInt n; } GoString;
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 GetLargeStruct_return* GetLargeStruct(GoInt p0);
extern void FreeLargeStruct(GetLargeStruct_return* p0);
/* Return type for GetLargeStruct2 */
struct GetLargeStruct2_return {
char* r0;
GoInt r1;
};
extern struct GetLargeStruct2_return GetLargeStruct2(GoInt p0);
extern void FreeCBytes(char* p0);
#ifdef __cplusplus
}
#endif
#include <Windows.h>
#include <stdio.h>
#include "sample3.h"
typedef GetLargeStruct_return* (*funcPtrGetLargeStruct)(GoInt p0);
typedef void (*funcPtrFreeLargeStruct)(GetLargeStruct_return* p0);
typedef struct GetLargeStruct2_return (*funcPtrGetLargeStruct2)(GoInt p0);
typedef void (*funcPtrFreeCBytes)(char* p0);
int main(){
HMODULE h = LoadLibraryA("sample3.dll");
if (NULL == h || INVALID_HANDLE_VALUE == h)
{
return -1;
}
funcPtrGetLargeStruct pfGetLargeStruct = (funcPtrGetLargeStruct)GetProcAddress(h,"GetLargeStruct");
funcPtrFreeLargeStruct pfFreeLargeStruct = (funcPtrFreeLargeStruct)GetProcAddress(h,"FreeLargeStruct");
if (pfGetLargeStruct)
{
GetLargeStruct_return* result = pfGetLargeStruct(5);
if (result)
{
printf("GetLargeStruct(5) return %x %d\r\n",result->Data,result->DataLen);
if (pfFreeLargeStruct)
{
pfFreeLargeStruct(result);
}
}
}
funcPtrGetLargeStruct2 pfGetLargeStruct2 = (funcPtrGetLargeStruct2)GetProcAddress(h,"GetLargeStruct2");
funcPtrFreeCBytes pfFreeCBytes = (funcPtrFreeCBytes)GetProcAddress(h,"FreeCBytes");
if (pfGetLargeStruct)
{
GetLargeStruct2_return result = pfGetLargeStruct2(5);
printf("GetLargeStruct2(5) return %x %d\r\n",result.r0,result.r1);
if (pfFreeCBytes)
{
pfFreeCBytes(result.r0);
}
}
FreeLibrary(h);
return 0;
}
運行以後的輸出:
本文只講述C/C++怎麼調用golang程序,細節、注意事項及其餘在後續隨筆中介紹。
https://github.com/golang/go/issues/18412