go与c++链接示例

go lang与c/c++的链接示例:

foo.hpp

1
2
3
4
5
6
7
8
9
10
11
12
13
//foo.hpp
#ifndef _FOO_HPP_
#define _FOO_HPP_
 
template<typename T>
T add(const T& lhs,const T& rhs)
{
    return lhs+rhs;
}
 
void display();
 
#endif //_FOO_HPP_

foo.cpp

1
2
3
4
5
6
7
8
//foo.cpp
#include "foo.hpp"
#include <iostream>
 
void display()
{
    std::cout<<"this message is from foo.cpp -display"<<std::endl;
}

foo_wrap.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//foo_wrap.h
#ifndef _FOO_WRAP_H_
#define _FOO_WRAP_H_
 
#ifdef __cplusplus
extern "C" {
#endif
 
//add function family
int add_int_wrap(int lhs,int rhs);
float add_float_wrap(float lhs,float rhs);
 
//display some message
void display_wrap();
 
#ifdef __cplusplus
}
#endif
#endif //_FOO_WRAP_H_

foo_wrap.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//foo_wrap.cpp
#include "foo_wrap.h"
#include "foo.hpp"
 
//add function family
int add_int_wrap(int lhs,int rhs)
{
    return add<int>(lhs,rhs);
}
float add_float_wrap(float lhs,float rhs)
{
    return add<float>(lhs,rhs);
}
 
//display
void display_wrap()
{
    return display();
}

foo.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//foo.go
package main
 
// #cgo CFLAGS: -I./
// #cgo LDFLAGS: -L./ libfoo.a -lstdc++
// #include "foo_wrap.h"
import "C"
import "fmt"
 
func main() {
    //test add family
    //int
    var a,b int32 = 1,2
    rsi := C.add_int_wrap(C.int(a),C.int(b))
    fmt.Printf("C.add_int_wrap(%d,%d)=%d\n",a,b,rsi)
    //float
    var c,d float32 = 1.3,2.5
    rsf := C.add_float_wrap(C.float(c),C.float(d))
    fmt.Printf("C.add_int_wrap(%f,%f)=%f\n",c,d,rsf)
     
    //display
    fmt.Println("message from C:")
    C.display_wrap()
}

编译脚本build.sh:

1
2
3
4
5
6
7
8
#!/bin/sh<br>#build c/c++ source code
g++ -c foo.cpp
g++ -c foo_wrap.cpp
ar rcs libfoo.a foo.o foo_wrap.o
 
#build go source code
go build foo.go
./foo
posted @   *神气*  阅读(538)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 单线程的Redis速度为什么快?
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示