Golang calling a dynamic library

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

Test the Dynamic Library

Test_so.h

int test_so_func (int A,int b);

Test_so.c

" test_so.h " int test_so_func (int A,int  b) {    return A *b;}

Generate so

gcc -shared./test_so.c-o test_so.so

Copy so files to the Golang project directory

Golang project directory, establish

Load_so.h

int do_test_so_func (int A,int b);

Load_so.c

#include"load_so.h"#include<dlfcn.h>intDo_test_so_func (intAintb) {    void*handle; typedefint(*FPTR) (int,int); Handle= Dlopen ("./test_so.so",1); Fptr fptr= (fptr) dlsym (handle,"Test_so_func"); intresult = (*fptr)    (A, B); returnresult;}

Test.go

Package Main /* #include "load_so.h" #cgo ldflags:-ldl */  "C""fmt"func Main () {    Fmt. Println ("20*30=", C.do_test_so_func ())} 

Compile and run.

Note: A great God in the Go call C, fell into a hole, address http://www.newjueqi.com/?p=106, the conclusion is

1./* */Comment The code next line must be import "C", middle cannot have blank line
2.import "C" must be a separate line and cannot be imported with other libraries

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.