UE4连接第三方库(lib和dll)

摘要:
写这个文章主要是被UE官方的wiki和answerhub误导了好久,这原本是一个很常见和基本的问题,可是不管是官方的wiki或者是论坛上的提问都十分散乱而且充斥各类错误,所以记录下这个在开发中时常遇到的问题。函数

在开发中常常遇到的问题就是加入某第三方库的支持,这样的第三方库每每属于无源码,并且多是静态lib或者是动态dll甚至二者皆有。UE4的编译管理用的是本身的UBT(unreal binary tool)所以连接第三方库的工做主要是编写UBT脚本。ui

1.以插件方式集成.
基本上这个是最推荐的集成第三方库的方式,由于可以很好的隔离你的代码和第三方代码的影响,在UE4的源码里也能够看到不少第三方库都是这么集成的,好比paper2D,leapmotion等等。在UE4中新建插件的方式略去不表,当你新建完你的插件以后,你会在插件的代码目录下看到一个插件

xxx.build.cs

接下来要作的就是修改这个脚本:code

获得当前路径orm

private string ModulePath
{
   get { return ModuleDirectory; }
}

关于第三方库放的位置,通常是在plugin的源码同级文件夹下建一个ThirdParty文件夹,里面放上include lib等等。ci

获得ThirdParty文件夹的路径开发

private string ThirdPartyPath
{
        get { return Path.GetFullPath(Path.Combine(ModulePath,"../../ThirdParty/")); }
}

为工程添加include第三方库的头文件路径
在模快的构造函数里加上:get

PublicIncludePaths.AddRange(
        new string[] { 
             Path.Combine(ThirdPartyPath, "xxx", "Include"),
        }
        );
            
    
PrivateIncludePaths.AddRange(
        new string[] {
            Path.Combine(ThirdPartyPath, "Foxit", "Include"),
        }
        );

连接第三方库的Lib源码

接下来须要在编译工程时加入第三方静态库的连接,静态连接属于工程在编译期间作的事情,所以这块须要经过cs脚本完成,而dll动态连接库的加载是运行期的事,所以须要在cpp文件中执行。string

咱们新建一个叫LoadxxxLib的函数,并把它放在模块的构造函数结尾执行:

public bool LoadxxxLib(TargetInfo Target)
    {
        bool isLibararySupported = false;
        if ((Target.Platform == UnrealTargetPlatform.Win64) || (Target.Platform == UnrealTargetPlatform.Win32))
        {
            isLibararySupported = true;
            string PlatformString = (Target.Platform == UnrealTargetPlatform.Win64) ? "Win64" : "Win32";
            PublicAdditionalLibraries.Add(Path.Combine(LibraryPath, PlatformString + ".lib"));
            PublicDelayLoadDLLs.Add(PlatformString + ".dll");
            RuntimeDependencies.Add(new RuntimeDependency(LibraryPath + PlatformString + ".dll"));
        }
        return isLibararySupported;
    }

这样就能够保证在编译期连接上咱们的第三方lib。

连接动态DLL

这个工做须要在plugin的运行期完成,在插件的source文件下找到一个与插件名字同名的cpp文件打开。会看到一个StartupModule的函数,咱们须要在这里获得dll文件的handle。

在StartupModule中添加下面的代码:

void FXXXModule::StartupModule()
{
#if PLATFORM_64BITS
    FString platform = TEXT("win64.dll");
#else
    FString platform = TEXT("win32.dll");
#endif
    FString path = IPluginManager::Get().FindPlugin("XXX")->GetBaseDir(); 
    FString dllpath = path + "/ThirdParty/XXX/Lib/" + platform;
    PdfDllHandle = FPlatformProcess::GetDllHandle(*dllpath);
    if (!PdfDllHandle)
    {
        UE_LOG(LogTemp, Warning, TEXT("Failed to load PDF library."));
    }
}

这里咱们用的是PluginManager找到的插件所在的路径,值得注意的是使用这个函数时须要在build.cs
中加入

PrivateDependencyModuleNames.AddRange(
            new string[]
            {
                ...
                "Projects",
            }
            );

不然工程会连接出错。

相关文章
相关标签/搜索