Golang's CGO---call C + + Dynamic library functions

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

Previously said Golang call C code can be through CGO or swig, and CGO is a 不能使用 C + + related things, such as the standard library or C + + object-oriented features. What to do, the C + + function function is encapsulated into the interface, and then compiled into a dynamic library, or the function is relatively simple can be embedded directly into the go source file.
CGO is used on Linux platforms where cross compilers can be configured on the Windows platform.

动态库头文件:myfuns.h
#pragma once#include <stdio.h>#include <string.h>#include <stdlib.h>#include <stdbool.h>void fun1();void fun2(int a);int func3(void **b);// others
动态库名:myfuns.so

  

项目简化结构:
|-project|  |-lib|  |  |-myfuns.so|  |-include|  |  |-myfuns.h|  |-src|  |  |-main.go|  |-pkg|  |-bin
go链接动态库:main.go
package main/*#cgo CFLAGS : -I../include#cgo LDFLAGS: -L../lib -lmyfuns#include "myfuns.h"*/import"C"import (    "fmt")func main() {    // 调用动态库函数fun1    C.fun1()    // 调用动态库函数fun2    C.fun2(C.int(4))    // 调用动态库函数fun3    var pointer unsafe.Pointer    ret := C.fun3(&pointer)    fmt.Println(int(ret))}

By CFLAGS Configuring the Compile option, you LDFLAGS can link a dynamic library under a specified directory. One thing to note here is that import "C" there is no blank line next to the comment.

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.