完善动态库加载功能并添加详细注释

This commit is contained in:
kingecg 2025-09-21 14:13:22 +08:00
parent b3c6f070da
commit ae083e9d9d
1 changed files with 17 additions and 0 deletions

View File

@ -1,3 +1,5 @@
// Package interceptor 提供了动态加载和调用共享库函数的功能。
// 该包使用purego库实现跨平台的动态库加载支持Windows的DLL和Linux的SO文件。
package interceptor package interceptor
import ( import (
@ -9,11 +11,15 @@ import (
"github.com/ebitengine/purego" "github.com/ebitengine/purego"
) )
// funcType 定义了函数的参数类型和返回值类型。
// 用于在动态加载库函数时指定函数签名。
type funcType struct { type funcType struct {
ParamTypes []string ParamTypes []string
ReturnTypes []string ReturnTypes []string
} }
// typeMap 将字符串类型名映射到对应的Go reflect.Type。
// 支持基本数据类型如int、float、string等以及特殊的"void"类型表示无返回值。
var typeMap = map[string]reflect.Type{ var typeMap = map[string]reflect.Type{
"int": reflect.TypeOf(int(0)), "int": reflect.TypeOf(int(0)),
"int32": reflect.TypeOf(int32(0)), "int32": reflect.TypeOf(int32(0)),
@ -26,6 +32,10 @@ var typeMap = map[string]reflect.Type{
"void": nil, // 用于表示无返回值 "void": nil, // 用于表示无返回值
} }
// makeFuncType 根据给定的参数类型和返回值类型字符串列表,创建对应的函数类型。
// paramTypes: 函数参数类型的字符串列表
// returnTypes: 函数返回值类型的字符串列表
// 返回: 创建的函数类型和可能的错误
func makeFuncType(paramTypes, returnTypes []string) (reflect.Type, error) { func makeFuncType(paramTypes, returnTypes []string) (reflect.Type, error) {
var in, out []reflect.Type var in, out []reflect.Type
@ -53,6 +63,11 @@ func makeFuncType(paramTypes, returnTypes []string) (reflect.Type, error) {
return reflect.FuncOf(in, out, false), nil return reflect.FuncOf(in, out, false), nil
} }
// loadLibrary 加载指定路径的动态库文件,并根据提供的函数映射表注册库中的函数。
// 如果库已经被加载过,则直接返回之前加载的实例。
// libPath: 动态库文件的路径
// libFuncMap: 库中函数名到函数类型的映射表
// 返回: 包含所有注册函数的接口实例
func (a *Ankointerceptor) loadLibrary(libPath string, libFuncMap map[string]funcType) interface{} { func (a *Ankointerceptor) loadLibrary(libPath string, libFuncMap map[string]funcType) interface{} {
libName := filepath.Base(libPath) libName := filepath.Base(libPath)
libName = strings.TrimSuffix(libName, filepath.Ext(".dll")) libName = strings.TrimSuffix(libName, filepath.Ext(".dll"))
@ -104,6 +119,8 @@ func (a *Ankointerceptor) loadLibrary(libPath string, libFuncMap map[string]func
return a.libMap[libName] return a.libMap[libName]
} }
// Close 关闭所有已加载的动态库句柄,释放资源。
// 应在不再需要使用动态库时调用此方法。
func (a *Ankointerceptor) Close() { func (a *Ankointerceptor) Close() {
for _, lib := range a.libhabdles { for _, lib := range a.libhabdles {
purego.Dlclose(lib) purego.Dlclose(lib)