编写UE4插件时添加第三方库的方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shenshen211/article/details/80539404

    UE4插件极大的提高了引擎的可扩展性,如果想添加新的功能,你不需要改动引擎的源码,只需要创建一个插件就能实现目的。但是在插件中有时会调用第三方库,UE4工程有自己的一套构建,通过*.build.cs文件来描述(传统的C++项目是通过VS工程文件来描述,你可以在工程中调价包含目录,依赖库等等),再该文件中,你通过特定的规则来添加包含目录,依赖库等等。

    先来说一下插件的目录结构,如下图所示:


重点说一下LibA.Build.cs文件:

    

Type = ModuleType.External;


        //string basePath = Path.GetDirectoryName(RulesCompiler.GetFileNameFromType(this.GetType()));
        //添加包含目录
        PublicIncludePaths.Add(
                // ... add public include paths required here ...
                Path.Combine(ModuleDirectory, "include")
                 );

        if (Target.Platform == UnrealTargetPlatform.Win64)
		{
            //添加库目录和依赖库
            PublicLibraryPaths.Add(Path.Combine(ModuleDirectory, "lib"));
            PublicAdditionalLibraries.Add("D.lib");

            //添加动态库目录
            PublicLibraryPaths.Add(Path.Combine(ModuleDirectory, "bin"));
            //设置延迟加载
            PublicDelayLoadDLLs.Add("A.dll");
            PublicDelayLoadDLLs.Add("B.dll");
            PublicDelayLoadDLLs.Add("C.dll");
            PublicDelayLoadDLLs.Add("D.dll");

            RuntimeDependencies.Add(new RuntimeDependency(Path.Combine(ModuleDirectory, "bin", "A.dll")));
            RuntimeDependencies.Add(new RuntimeDependency(Path.Combine(ModuleDirectory, "bin", "B.dll")));
            RuntimeDependencies.Add(new RuntimeDependency(Path.Combine(ModuleDirectory, "bin", "C.dll")));
            RuntimeDependencies.Add(new RuntimeDependency(Path.Combine(ModuleDirectory, "bin", "D.dll")));
        }

建议设置延迟加载,这样就可以在需要该模块的时候自己来控制dll的加载,一般设置在模块的StartMoudle函数中,如下所示:

FString DllPath = FPaths::EnginePluginsDir() + TEXT("TESTPlugin/Source/ThirdParty/LibA/bin/");
	FPlatformProcess::PushDllDirectory(*DllPath);
	AHandle = FPlatformProcess::GetDllHandle(*(DllPath + "A.dll"));
	BHandle = FPlatformProcess::GetDllHandle(*(DllPath + "B.dll"));
	CHandle = FPlatformProcess::GetDllHandle(*(DllPath + "C.dll"));
	DHandle = FPlatformProcess::GetDllHandle(*(DllPath + "D.dll"));
	FPlatformProcess::PopDllDirectory(*DllPath);

另外在模块结束函数ShutdownMoudle中不要忘记卸载dll,如下:

if (AHandle)
	{
		FPlatformProcess::FreeDllHandle(AHandle);
	}

	if (BHandle)
	{
		FPlatformProcess::FreeDllHandle(BHandle);
	}

	if (CHandle)
	{
		FPlatformProcess::FreeDllHandle(CHandle);
	}

	if (DHandle)
	{
		FPlatformProcess::FreeDllHandle(DHandle);
	}

在需要使用该库的模块加入依赖项就可以了,如下:

 PublicDependencyModuleNames.AddRange(
				new string[]
				{
					"Core",
					"CoreUObject",
                                        "AnimationCore",
                                        "LibA"
					// ... add other public dependencies that you statically link with here ...
				}
				);
到此一切ok。

猜你喜欢

转载自blog.csdn.net/shenshen211/article/details/80539404