golang的cgo支持調用C++的方法


1)swift,貌似官網的推薦

2)extern "C"

我使用后者,用起來比較爽,上代碼

c.h

1 #pragma once
2 
3 #ifdef __cplusplus
4 extern "C" {
5 #endif
6 void test();
7 #ifdef __cplusplus    
8 }
9 #endif

 

c.c

1 #include "cplus.hpp"
2 #include "c.h"
3 
4 void test() {
5     A *a = new B();
6     a->test();
7 }

 

cplus.hpp

 1 #pragma once
 2 
 3 class A {
 4     public:
 5         virtual void test();
 6 };
 7 class B: public A {
 8     public:
 9         void test();
10 };

cplus.cpp

#include <iostream>
#include "cplus.hpp"

using namespace std;

void A::test() {
    cout << "a" << endl;
}

void B::test() {
    cout << "b" << endl;
}

build.sh

1 g++ -o cplus.o -c cplus.cpp
2 g++ -o c.o -c c.c
3 ar r libc_test.so c.o cplus.o

test.go

 1 package main
 2 // #cgo LDFLAGS: -L . -lc_test -lstdc++
 3 // #cgo CFLAGS: -I ./
 4 // #include "c.h"
 5 import "C"
 6 
 7 func main(){
 8     
 9     C.test()
10     
11 }

執行順序

1 ./build.sh
2 go build test.go

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM