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() )
}

猜你喜欢

转载自blog.csdn.net/weixin_55305220/article/details/118755989