最近项目有个需求,需要为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 #includeclass 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中调用sdkmain.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}
注意:
- import "C" 与cgo编译声明不能有空行
- 需要使用-I -L指定头文件和库文件路径
- golang不支持c++,因此sdk定义需要包函在extern "C" 中
- 需要引入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



