CGO封装模版

2020-05-16  本文已影响0人  Lyudmilalala

C++ API classes

C++ function header -- test.h

#ifndef __TEST_H__
#define __TEST_H__

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <iostream>

class Test {
public:
    void SayHello(const char* s);
};

#endif

C++ function class -- test.cpp

#include <test.h>

void Test::SayHello(const char* s) {
    std::cout << s << " from test class.\n";
}

C wrapper for all C++ functions

C wrapper header -- cwrap.h

#ifndef __CWRAP_H__
#define __CWRAP_H__

#ifdef __cplusplus
extern "C" {
#endif
void SayHelloC(const char* s);
#ifdef __cplusplus
}
#endif

#endif

C wrapper class -- cwrap.cpp

#include "test.h"
#include "cwrap.h"

void SayHelloC(const char* s) {
    Test ctx;
    ctx.SayHello(s);
}

Go class imports the C++ library

main.go

package main

/*
#include <cwrap.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
*/
import "C"
import "fmt"

func main() {
    SayHelloC("Hello World C++")
}

func SayHelloC(msg string) {
    C.SayHelloC(C.CString(msg))
}

//export SayHelloGo
func SayHelloGo(msg *C.char) {
    fmt.Print(C.GoString(msg))
}
上一篇 下一篇

猜你喜欢

热点阅读