SoFunction
Updated on 2025-05-23

How to call C dynamic library functions

Go calls C dynamic library functions

Method one

  • To directly call the dynamic library, you need to have header files;
  • If not, you need to write another dynamic library to call it;
  • The process is quite cumbersome;

Method 2

  • Directly use cgo to call;
  • Use dlopen to call dynamic libraries;
  • It is more convenient to be on the same file as Go code;

1 Convert strings and ints to each other;

2 Memory is manually released;

!!! go calls C dynamic library does not support cross-compilation!

package main


/*
 #include <>
 #include <>
 #include <>
 #include <>
 #cgo LDFLAGS: -ldl

 struct Hardware_API_Result {
    int result;
    char json[256];
 };


 char* getSysTime(){
    // Manually load the so dynamic library at the specified location
	 void* handle = dlopen("", RTLD_LAZY);
	 struct Hardware_API_Result (*getSysT)();

	 //Operate the handle and symbol according to the dynamic link library, and return the corresponding address of the symbol.
	 getSysT = dlsym(handle, "get_system_time");

	 //struct MidStruct midres;
	 struct Hardware_API_Result r;
	 r = getSysT();

	 //static char* cj="404"; Static variables cannot be used, multiple threads call, the value will be overwritten; Test: The log output in multiple calls to go is garbled
	 char * cj;
	 cj = (char *)malloc(256);
	 strcpy(cj,"404");
	 //
	 if(==0){
	    strcpy(cj,);
	 }
	 dlclose(handle);
	 return cj;
 }
 int start4G(){
	 void* handle = dlopen("", RTLD_LAZY);
	 int (*start4G)();
	 start4G = dlsym(handle, "start_4g");
	 int rv=start4G();
	 dlclose(handle);
	 return rv;
 }

 int ping(char* cip){
     void* handle = dlopen("", RTLD_LAZY);
	 struct Hardware_API_Result (*midFuncName)( char* );
     midFuncName = dlsym(handle, "ping");
	 struct Hardware_API_Result midres;
     midres=midFuncName(cip);
	 int rvi=;
     dlclose(handle);

     return rvi;
 }


 */
import "C"
import (
	"fmt"
	"unsafe"
)


/*
 Get system time
 json format: {"local_time":2020-03-23 ​​03:02:46.795268}
 */
func getSystime() string {
    //C medium pointer	sip:=()
	//Convert to go string	si:=(sip)
	//Release the pointer in c	((sip))
	return  si
}
/*
 Start 4g, return 0 after successful startup
 */
func start4G() int{
	// Type c	mrv:=C.start4G()
	//Convert to go int type	rv:=int(mrv)
	return rv
}


/**
 Determine whether an IP can be pinged, and a value of 0 indicates that it is pinged.
 */
func ping(ip string)int{
	cip := (ip)
	mrv:=(cip)
	rv:=int(mrv)
	((cip))
	return rv
}

Reference method 1

  
 (signed char)  
 (unsigned char)  
  
 (unsigned short)  
  
 (unsigned int)  
  
 (unsigned long)  
 (long long)  
 (unsigned long long)  
  
.   
  
  
 (void*)  
  
// Go string to C string  
func (string) *  
  
var val []byte  
(*)((&val[0]))

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.