网络大多在写怎么用go调用c,而没有写怎么调用c++。
1、首先,我们创建文件目录
2、 main.go
package main
import (
"./ndnKeyChain"
)
func main(){
ndnKeyChain.Sign() ;
}
3、keyTool.cpp
通过C调用C++的方式,这里注意keyTool.cpp,一定要以 .cpp或.cxx作后缀,不要用 .c 。
#include <stdio.h>
#include "keyTool.h"
#include "ndnKeyTool.h"
void sign(){
NDNKeyTool ndnKeyTool ;
}
4、keyTool.h
#ifndef _KEYTOOL_H_
#define _KEYTOOL_H_
#ifdef __cplusplus
extern "C" {
#endif
void sign() ;
#ifdef __cplusplus
}
#endif
#endif
5、ndnKeyChain.go
这里注意 import "C" 与前面的注释之间不要有空行
package ndnKeyChain
/*
#cgo CXXFLAGS: -std=c++14 // 为g++ 添加编译选项
#cgo LDFLAGS: -ljsoncpp // 为g++ 添加静态链接库选项
#include "keyTool.h"
*/
import "C" //import "C" 与注释之间不要有空行
func Sign(){
C.sign() ;
}
6、ndnKeyTool.cpp
#include <iostream>
#include "ndnKeyTool.h"
using namespace std;
NDNKeyTool::NDNKeyTool(){
Json::Value root ;
root["name"] = "wgh" ;
root["age"] = 100 ;
cout << root.toStyledString() << endl ;
cout << "hello" << endl ;
cout << to_string(1000.5) << endl ;
//pthread_t mtid ;
}
NDNKeyTool::~NDNKeyTool(){
}
7、ndnKeyTool.h
#ifndef _NDNKEYTOOL_H_
#define _NDNKEYTOOL_H_
#include <jsoncpp/json/json.h>
#include <pthread.h>
class NDNKeyTool
{
public:
NDNKeyTool();
~NDNKeyTool();
private:
/* data */
};
#endif