Golang's CGO supports calling C + + methods

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

C + + extern "C"

C.h

1 #pragma once2 3 #ifdef __cplusplus4 extern "C" {5 #endif6 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         V OID 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.cpp2 g++-o c.o-c c.c3 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}
  

Execution order

1./build.sh2 Go Build test.go
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.