我正试图在Go中调用C ++。
sparkle_windows.h:
#ifndef GO_WINSPARKLE_H
#define GO_WINSPARKLE_H
#ifdef __cplusplus
#include <QResource>
#include "winsparkle.h"
extern "C" {
#endif
void initWinSparkle()
{
win_sparkle_set_dsa_pub_pem(reinterpret_cast<const char *>(QResource(":/WinSparkle/dsa_pub.pem").data()));
win_sparkle_init();
}
#ifdef __cplusplus
}
#endif
#endif
main_windows.go:
package main
/*
#cgo CPPFLAGS: -I ${SRCDIR}/WinSparkle/include
#cgo LDFLAGS: -L${SRCDIR}/WinSparkle/Release -lWinSparkle -lsparkle_windows -lstdc++
#include "sparkle_windows.h"
*/
import "C"
func main() {
C.initWinSparkle()
}
和错误:
In file included from .\main_windows.go:10:0:
./sparkle_windows.h: In function 'initWinSparkle':
./sparkle_windows.h:15:30: error: 'reinterpret_cast' undeclared (first use in this function)
win_sparkle_set_dsa_pub_pem(reinterpret_cast<const char *>(QResource(":/WinSparkle/dsa_pub.pem").data()));
答案 0 :(得分:1)
cgo无法编译C ++,因此您需要将c ++函数放在.cpp文件中,然后使用c ++编译器进行编译。然后生成一个库,仅将函数原型放在.h文件中。
.h文件应为纯C,例如您不能将c ++类型用作函数参数。
这是一个简单的示例(在Linux上使用g ++ / ar创建一个静态库):
cpplink_test / cpp / cpplink.cpp:
#include <iostream>
#include "cpplink.h"
extern "C" void helloCpp()
{
std::cout << "Hello from Cpp !!!!\n";
}
cpplink_test / cpp / cpplink.h:
#ifdef __cplusplus
extern "C" {
#endif
void helloCpp();
#ifdef __cplusplus
}
#endif
编译并生成静态库(来自cpp /目录):
g++ -fPIC -c cpplink.cpp
ar cru libcpplink.a cpplink.o
ranlib libcpplink.a
cpplink_test / main.go:
package main
/*
#cgo CPPFLAGS: -I${SRCDIR}/cpp
#cgo LDFLAGS: -L${SRCDIR}/cpp -lcpplink -lstdc++
#include <cpplink.h>
*/
import "C"
import "fmt"
func main() {
fmt.Println("Hello GO")
C.helloCpp()
}
构建并运行:
go build
./cpplink_test
输出:
Hello GO
Hello from Cpp !!!!
如果您在Windows上,则C ++库创建可能会略有不同。