How does golang parse c-language so files provided by third-party companies?

I think most of the dynamic libraries for parsing the C language use the C package, but this package requires .h files. Now there are only so files, can you load so files directly like python"s ctype package?

Mar.14,2021

you need to know how to call the (output) interface of that so file, which is usually described in the SDK document or in the .h header file.

knows the calling method. If the * .h file is missing, you can find out the output interface (function) of the so file through some commands, such as

nm -D --defined-only xxx.so

or reverse engineering to resolve the interface (and parameters).

< hr >

for example, demonstrate how to call the int add (int a, int b) interface function of libadder.so .

File structure

 main.go            // 
 shared-lib
     adder.c        // so 
     adder.h
     libadder.so    //  Makefile 
     Makefile

File contents

adder.h

-sharpifndef _ADDER_H_
-sharpdefine _ADDER_H_

int add(int a, int b);

-sharpendif

adder.c

int add(int a, int b)
{
    return a + b;
}

Makefile

libadder.so: adder.c
    gcc -shared -Wall -O2 -std=c11 -fPIC -o $@ $^

main.go

package main

/*
-sharpcgo CFLAGS: -Ishared-lib/
-sharpcgo LDFLAGS: -Lshared-lib/ -ladder
-sharpinclude <adder.h>
*/
import "C"
import "fmt"

func main() {
    fmt.Println("1 + 2 = ", C.add(1, 2))
}

compile using

  1. generate so file: make-C shared-lib
  2. run the go file: LD_LIBRARY_PATH=$ (pwd) / shared-lib go run main.go
Menu