c++ - 在C++中使用Go

标签 c++ go shared-objects object-files

Linux的Debian克星
go版本go1.11.6 linux/amd64
gcc版本8.3.0(Debian 8.3.0-6)
libmylib.go

package main

import "C"

import (
    "fmt"
)

func say(text string) {
    fmt.Println(text)
}

func main(){}
mylib.h
#ifndef MY_LIB_H
#define MY_LIB_H

#include <string>

void say(std::string text);

#endif
main.cpp
#include <string>
#include "mylib.h"

using namespace std;

int main() {
    string text = "Hello, world!";

    say(text);

    return 0;
}

CGO_ENABLED=1 go build -o libmylib.so -buildmode=c-shared libmylib.go


g++ -L/path/to/lib/ -lmylib main.cpp -o my-test-program


/usr/bin/ld: /tmp/ccu4fXFB.o: in function 'main': main.cpp:(.text+0x53): undefined reference to `say(std::__cxx11::basic_string<char, std::char_traits, std::allocator >)'
collect2: error: ld returned 1 exit status


更改:package main -> package mylib

CGO_ENABLED=1 go build -o libmylib.so -buildmode=c-shared libmylib.go


-buildmode=c-shared requires exactly one main package

最佳答案

在C++版本中,必须使用GoString而不是std::string。您收到的错误消息是由于类型不匹配,表现为链接时错误。
参见the cgo reference
这是一个工作示例。与您有一些区别。需要使用//export指令将函数包含在生成的头文件中,参数是*C.char而不是stringGoString。 C++代码使用cgo生成的 header ,并且必须从静态字符串中删除const(因为go没有类似C的const)。
libmylib.go

package main

import "C"

import (
    "fmt"
)

//export say
func say(text *C.char) {
    fmt.Println(C.GoString(text))
}

func main() {}
main.cpp
#include "libmylib.h"

int main(void) {
    say(const_cast<char*>("hello world"));

    return 0;
}
命令
这将编译go文件,在当前目录中生成libmylib.solibmylib.h
go build -o libmylib.so -buildmode=c-shared libmylib.go
编译C++程序,将其链接到上面的共享库:
g++ -L. main.cpp -lmylib -o hello_program
要运行该程序,需要将LD_LIBRARY_PATH设置为当前目录。如果安装了程序并将共享库放在一个明智的位置,那将是不同的。
LD_LIBRARY_PATH=. ./hello_program

关于c++ - 在C++中使用Go,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62977352/

相关文章:

c++ - 通知前完成手动解锁

go - 编码(marshal)时间带小数点的时间

python - 在 Python 中导入 C++ 共享对象时出现段错误

C++ vector 和段错误

c++ - 在 Windows 服务中使用 SAPI 进行简单的文本转语音

git - 使用 git 设置正确的 Golang 目录结构以在自定义包上使用 go build

go - 在 os.Exit 被标记后不应该无法访问的代码

c++ - 如何调用通过使用 dlopen 加载共享对象运行时创建的对象的方法

android - 如何在 IntelliJ 中添加多个 native 库 (.so) 文件

c++ - Boost::Regex 段错误(我认为)