【UE4】调用外部链接库:dll动态库

加载

  • 方式一
    // dll内的函数引用声明
    typedef void(*_Initial)(
    char* thisPCID,
    char* thisConnectioninfo,
    char* thisExpVersion,
    char* thisSessionlD
    );
    
    void *DLLHandle;
    _Initial DLL_Initial;
      //加载
    bool UDLLTest::DLL_Init() {
        FString filePath = FPaths::Combine(*FPaths::GamePluginsDir(), TEXT("DLL/"), TEXT("test.dll"));
        if (FPaths::FileExists(filePath)) {
            UE_LOG(LogTemp, Log, TEXT("%s"), *filePath);
            // 绑定dll
            DLLHandle = FPlatformProcess::GetDllHandle(*filePath);
            if (DLLHandle != NULL) {
                DLL_Initial=NULL;
               
                //绑定函数
                FString procName = "Initial"; // dll里的函数名
                DLL_Initial = (_Initial)FPlatformProcess::GetDllExport(DLLHandle, *procName); 
                if(DLL_Initial != NULL){
                    UE_LOG(LogTemp, Log, TEXT("DLL_Initial import succ"));
                    return true;
                }     
            }
        }
        return false;
    }
    
    //释放
    void UDLLTest::DLL_Free() {
        if(DLLHandle !=NULL){
            DLL_Initial = NULL;
            FPlatformProcess::FreeDllHandle(DLLHandle );
            DLLHandle = NULL;
        }
    }
    
  • 方式二 (当使用方法一引用不到 dll 的时候,可以尝试使用该方法)
    SetDllDirectory(*filePath);
    DllHandle = LoadLibrary(TEXT("test.dll"));
    ...
    

运行时依赖性

  • 打包游戏时为在可执行文件旁暂存第三方DLL,可在 build.cs中声明其为运行时依赖性。
    RuntimeDependencies.Add(Path.Combine(PluginDirectory, "Binaries/Win64/Foo.dll"));
    
  • 此操作假设DLL已存在于给定目录中,插件将在该位置手动进行加载。若希望在编译时将DLL复制到可执行文件使用的相同输出目录,可通过重载 RuntimeDependencies.Add 方法执行。
    RuntimeDependencies.Add("$(TargetOutputDir)/Foo.dll", Path.Combine(PluginDirectory, "Source/ThirdParty/bin/Foo.dll"));
    

参考

posted @ 2021-11-05 00:22  砥才人  阅读(1704)  评论(0编辑  收藏  举报