zoukankan      html  css  js  c++  java
  • Go与C/C++ 互相调用

    1、Go调用C:在go文件里调C(以下代码中除了开头的注释之外,其他注释不可删除)

    /*
     * go 和 C 互调用程序
     */
    
    package main
    
    /*
    int Add( int a, int b ) {
          return a + b;
    }
    */
    import "C"
    import (
          "fmt"
    )
    
    func main() {
          fmt.Println(C.Add(1, 2))
    }
    

    上面的C代码虽然被“注释”了,但是Go可以直接调

    2、Go调用C:通过.h头文件调(以下代码中除了开头的注释之外,其他注释不可删除)

    /*
     * go 和 C 互调用程序
     */
    
    package main
    
    /*
    #include "MyHeadFile.h"
    */
    import "C"
    import (
          "fmt"
    )
    
    func main() {
          fmt.Println(C.MyFunc("Hello"))
    }
    

    上面代码以注释的方式导入MyHeadFile.h头文件,然后可以直接使用其中的函数

    3、Go生成动态库dll(以下代码中除了开头的注释之外,其他注释不可删除)

    /*
     * Go生成动态库的命令(Windows平台需安装mingw-w64):
     * go build -o hello.dll -buildmode=c-shared hello.go
     * go build -o hello.so -buildmode=c-shared hello.go
     */
    package main
    
    import "C"
    import (
          "fmt"
    )
    
    //export HelloGolang
    func HelloGolang() {
          fmt.Println("HelloGolang")
    }
    
    func main() {
          fmt.Println("main")
    }
    

    4、示例:Go调C并返回

    package main
    
    /*
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define LEN 1024
    
    char* Foo( char *input ) {
        char* res = malloc( LEN * sizeof( char ) );
        sprintf( res, "%s %s", input, "World!" );
        return res;
    }*/
    import "C"
    import (
        "fmt"
        "unsafe"
    )
    
    func getID() string {
        cs  := C.CString( "Hello" )
        res := C.Foo( cs )
        str := C.GoString( res )
        C.free( unsafe.Pointer( cs ) )
        C.free( unsafe.Pointer( res) )
        return str
    }
    
    func main() {
        fmt.Println( getID() )
    }
    

    未完待续...

  • 相关阅读:
    2017 Multi-University Training Contest
    NTT模板
    重庆OI2017 小 Q 的棋盘
    用TensorFlow2.0构建分类模型对数据集fashion_mnist进行分类
    读取keras中的fashion_mnist数据集并查看
    基本类型和引用类型
    idea快捷键
    pytorch的torch.nn.CrossEntropyLoss()
    高斯模糊和高斯双边滤波
    opencv之模糊操作
  • 原文地址:https://www.cnblogs.com/isky0824/p/13614318.html
Copyright © 2011-2022 走看看