在c++ 程序中,有时我们需要根据客户需求,添加短信提醒/短信验证等功能,然而,市场上的大部分短信平台,对c/c++支持都不算友好。
有人,自己用c/c++从头到尾,自己实现了一套短信的c++ sdk,但是用起来,呵呵。。。
但是我们换个角度想一想,短信平台提供的SDK 大部分都包含 python,java,go...等等。
1、python 和 java 都是解释性语言,可以用c++调用python的c库 和jni,但是这两种语言用c++调用起来就很繁琐了,要求稍微有些高,程序做好后,可能出现各种意想不到的错误,很可能程序崩溃,所所以pass掉。
2、用 go 版本sdk,就没有这么多烦恼。因为go是编译型、跨平台的语言,在各种平台上都是能以机器码的形式运行。另外go的模块,扩展名都为 .a,与c/c++语言的静态库,存在着千丝万缕的联系,我们可以通过go的工具把go程序直接编译位静态库,供给c++调用。
拿阿里云短信平台举例
1、首先安装go 运行环境
Windows直接下载安装包
ubuntu 18.04 : sodu apt-get install golang
2、下载依赖包
go get -u github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests
go get -u github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi
hello.go代码类似如下
package main
import (
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
"C"
)
func main() {
}
//export SendSms
func SendSms(phoneNumber,params string){
client, err := dysmsapi.NewClientWithAccessKey("cn-hangzhou", "阿里云的accessKeyId", "accessKeySecret")
request := dysmsapi.CreateSendSmsRequest()
request.Scheme = "https"
request.PhoneNumbers = phoneNumber
request.SignName = "XXXXX"
request.TemplateCode = "XXXXX"
request.TemplateParam = params
response, err := client.SendSms(request)
if err != nil {
fmt.Print(err.Error())
}
fmt.Printf("response is %#v\n", response)
}
3、生成静态库
go build -buildmode=c-archive hello.go
执行完毕后就会生成 hello.a 和 hello.h两个文件,其中hello.a为静态库,hello.h为c++调用的头文件。
把这两个文件添加到c++ 工程,我们就会很愉快的调用函数SendSms了。
#include <QCoreApplication>
#include <hello.h>
#include <string>
void __sendSms(const std::string &phoneNumber,const std::string & params){
GoString gphone{phoneNumber.c_str() ,static_cast<ptrdiff_t>(phoneNumber.length()) };
GoString gparams{params.c_str(),static_cast<ptrdiff_t>(params.length())};
SendSms(gphone,gparams);
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
__sendSms("1350000000","{\"name\":\"1357656\",\"place\":\"山东\",\"time\":\"2019-11-20\",\"type\":\"警报\"}");
return a.exec();
}