栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

生产环境使用CGO

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

生产环境使用CGO

最近项目有个需求,需要为app提供算子API。算子为pytorch训练生成的深度模型,并用libtorch封装提供sdk。c++服务是一个较好的解决方案,只需要在服务编译中添加sdk的编译依赖就行了,但是c++服务搭建成本太高,折中一下,选择CGO方案。

本文不介绍如何进行深度模型训练,sdk编写,以及golang服务的搭建,仅仅就golang和c++接口交互做介绍。

c++算子sdk生成

sdk包为一个库文件加一个头文件,示例项目目录如下所示

 toos.h 

#ifndef TOOLS_H
#define TOOLS_H

#ifdef __cplusplus
extern "C"{
#endif

int cloud_image_classification(void *pInstance, char *imgfile, char *pJsonResult);


int cloud_create_instance(char* path, char* name, void **pInstance);

#ifdef __cplusplus
}
#endif

#endif

tools.cc

#include "model.h"

#include "tools.h"
#include 
#include 


int cloud_image_classification(void *pInstance, char *imgfile, char *pJsonResult) {
    DeepModel* dm = static_cast(pInstance);
    
    std::string buff = dm->predict(imgfile);
    strcpy(pJsonResult, buff.c_str());    
    return 0;   
}

int cloud_create_instance(char* path, char* name, void **pInstance) {
    *pInstance = new DeepModel(path, name);
    return 0;
}

model.h

#ifndef MODEL_H
#define MODEL_H

#include 

class DeepModel {
public:
    DeepModel(const char *path, const char*name):path(path), name(name) {}
    
    std::string predict(char *imgfile);
private:
    std::string path;
    std::string name;
};

#endif

model.cc

#include "model.h"

std::string DeepModel::predict(char *imgfile) {
    return "{"class": 0}";
}

使用命令g++ -fPIC -shared -o lib/libtools.so include/*.cc -lstdc++ 生成so库

Go中调用sdk

main.go

package main

//#cgo CFLAGS: -I./include
//#cgo LDFLAGS: -L./lib -ltools -Wl,-rpath,lib
//#include "tools.h"
import "C"

import (
	"fmt"
	"unsafe"
)

func main() {
	var pinstance unsafe.Pointer
	C.cloud_create_instance(C.CString("abc"), C.CString("def"), &pinstance)

	result := make([]byte, 1024)

	C.cloud_image_classification(pinstance, C.CString("1.png"), (*C.char)(unsafe.Pointer(&result[0])))
	fmt.Println(string(result))
}

编译golang服务

go build -o main main.go

./main

{"class": 0}

注意:

  1. import "C" 与cgo编译声明不能有空行
  2. 需要使用-I -L指定头文件和库文件路径
  3. golang不支持c++,因此sdk定义需要包函在extern "C" 中
  4. 需要引入sdk的头文件,不然会报

./main.go:14:2: could not determine kind of name for C.cloud_create_instance
./main.go:18:2: could not determine kind of name for C.cloud_image_classification

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1029665.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号