我正在尝试将Golang脚本与现有的C共享库集成。 C共享库反过来在运行时加载其他共享库。
我想跑步的时候 去运行gotest.go
它抛出错误
./libtest.so: undefined reference to `dlopen'
./libtest.so: undefined reference to `dlclose'
./libtest.so: undefined reference to `dlerror'
./libtest.so: undefined reference to `dlsym'
collect2: error: ld returned 1 exit status
我已经创建了单独的C可执行文件,以便在运行时加载此libtest.so并且运行正常。
知道应该采取什么措施来解决这个问题吗?
我尝试过以下命令
sudo go build -compiler = gccgo -gccgoflags =“ - ltest”gotest.go
也尝试了命令
sudo go build -compiler = gccgo -gccgoflags =“ - ltest -ldl”gotest.go
还尝试了命令
go run gotest.go
===============================================
以下是我正在使用的代码
testapi.h
typedef Students{
char name[40];
int id;
} Student;
Student* getStudent();
test.c
#include <stdlib.h>
#include <stdio.h>
#include "mylib.h"
#include "testapi.h"
int rc = 0;
Student *s = 0;
Student* getStudent(){
rc = loadmylib(); //This function loads another shared library
if (!rc)
{
rc = initlib(); //This calls dlsym to get the necessary function from opened shared library
if (!rc)
{
s= (student *)malloc(sizeof(Student));
//use the function pointer received from dlsym to populate the Student struct 's'
}
}
return s;
}
我的gotest.go文件中有以下条目
package main
/*
#cgo CFLAGS: -I.
#cgo LDFLAGS: -L. -ltest -ldl
#include "testapi.h"
*/
import "C"
import (
"fmt"
)
type Student struct{
name string
id int
}
func main() {
st := C.getStudent()
fmt.Println("Name: ", string(st.name))
}
我已将testapi.h,gotest.go,mylib.h,libmylib.so,libtest.so复制到同一目录中。 然后运行命令
go run gotest.go
它抛出错误“错误:未定义引用'getStudent'”
我在这里做错了什么? 我应该运行命令
sudo go build -compiler = gccgo -gccgoflags =“ - ltest”gotest.go