UE4 加载第三方库

首先写一个第三方库

.h

#pragma once
#ifndef __MYTEST_LIB_H__
#define __MYTEST_LIB_H__
#include <string>
#include <iostream>

int Addd(int a, int b);

#endif

.cpp

#include "stdafx.h"
#include "MyDll.h"
int Addd(int a, int b) 
{ return a + b; }

.def


   LIBRARY MyThirdParty
   EXPORTS               
   Addd     

生成静态库lib

第一种,项目调用:

和Source同级目录下建个ThirdParty文件夹,在ThirdParty下再新建Includes和Libs文件夹,把上面的.h丢进Includes,lib丢进Libs

然后在项目Build.cs下添加:

using System.IO;
 private string ModulePath
    {
        get{ return ModuleDirectory; }//return Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name)); 
    }
    private string ThirdPartyPath
    {
        get { return Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/")); }
    }

在 public TTTTT(TargetInfo Target)下加上:同下LoadThirdPartyLib(Target);函数

       // PublicIncludePaths.Add(Path.Combine(ThirdPartyPath, "Includes"));
      //  PublicAdditionalLibraries.Add(Path.Combine(ThirdPartyPath, "Libs", "XXX.lib"));

接下来就可以在.h文件里#include你的第三方头文件了

第二种,插件调用:

同样在插件Source同级下新建ThirdParty文件夹,在ThirdParty下多一层MyTestLib文件夹,再往下新建Includes和Libs文件夹,把上面的.h丢进Includes,lib丢进Libs

然后在插件Build.cs下添加:

using System.IO;
private string ModulePath //第三方库
    {
        // get { return Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name)); }
        get { return ModuleDirectory; }
    }

    private string ThirdPartyPath//第三方库
    {
        get { return Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/")); }
    }
    private string MyLibPath //第三方库MyTestLib的目录
    {
        get { return Path.GetFullPath(Path.Combine(ThirdPartyPath, "MyTestLib")); }
    }

 public Test(ReadOnlyTargetRules Target) : base(Target)下添加一个 LoadThirdPartyLib(Target);函数,下面是函数实现

 public bool LoadThirdPartyLib(TargetInfo Target)
    {
        bool isLibrarySupported = false;
        if ((Target.Platform == UnrealTargetPlatform.Win64) || (Target.Platform == UnrealTargetPlatform.Win32))//平台判断
        {
            isLibrarySupported = true;
            System.Console.WriteLine("----- isLibrarySupported true");
            string PlatformSubPath = (Target.Platform == UnrealTargetPlatform.Win64) ? "Win64" : "Win32";
            string LibrariesPath = Path.Combine(MyLibPath, "Libs");
            PublicAdditionalLibraries.Add(Path.Combine(LibrariesPath,/* PlatformSubPath,*/ "MyThirdParty.lib"));//加载第三方静态库.lib
            PublicDelayLoadDLLs.Add(Path.Combine(LibrariesPath,/* PlatformSubPath,*/ "MyThirdParty.dll"));//加载第三方动态库.lib
            string MyDllPath = Path.Combine(LibrariesPath, "my.dll");
            RuntimeDependencies.Add(new RuntimeDependency(MyDllPath));
        }

        if (isLibrarySupported) //成功加载库的情况下,包含第三方库的头文件
        {
            // Include path
            System.Console.WriteLine("----- PublicIncludePaths.Add true");
            PublicIncludePaths.Add(Path.Combine(MyLibPath, "Includes"));
        }
        return isLibrarySupported;
    }

接下来就可以在.h文件里#include你的第三方头文件了
 

下面加载动态库

添加Source.def文件

   LIBRARY MyThirdParty
   EXPORTS               
   Addd   

生成动态库

默认加载dll是在项目的Binaries\Win64下  需要把dll放入这里

手动加载dll的方法的例子:

首先在build.cs添加"Projects"模块

	* Singleton-like access to this module's interface.  This is just for convenience!
	* Beware of calling this during the shutdown phase, though.  Your module might have been unloaded already.
	*
	* @return Returns singleton instance, loading the module on demand if needed
	*/
	static inline XXX& Get()
	{
		return FModuleManager::LoadModuleChecked<XXX>("XXX");
	}

	/**
	* Checks to see if this module is loaded and ready.  It is only valid to call Get() if IsAvailable() returns true.
	*
	* @return True if the module is loaded and ready to use
	*/
	static inline bool IsAvailable()
	{
		return FModuleManager::Get().IsModuleLoaded("XXX");
	}

DECLARE_LOG_CATEGORY_EXTERN(LogMyPlugin, Verbose, All);
void* DllHandle;
static inline bool IsAvailable()//.h
{
	return FModuleManager::Get().IsModuleLoaded("MyPlugin");
}


#include "IPluginManager.h"
#include "Paths.h"
#include "MessageDialog.h"
#include "WindowsPlatformProcess.h"
void MyPluginModule::StartupModule()
{
	if (IsAvailable())
	{
		UE_LOG(LogMyPlugin, Log, TEXT("%s"), TEXT("MyPlugin Module Started"));
	}
#if 1
	// Get the base directory of this plugin
	FString BaseDir = IPluginManager::Get().FindPlugin("MyPlugin")->GetBaseDir();

	// Add on the relative location of the third party dll and load it
	FString MSCLibraryPath;
#if PLATFORM_WINDOWS
#if PLATFORM_64BITS
	MSCLibraryPath = FPaths::Combine(*BaseDir, TEXT("Binaries/ThirdParty/MyPlugin/Win64/my_x64.dll"));
#else
	MSCLibraryPath = FPaths::Combine(*BaseDir, TEXT("Binaries/ThirdParty/MyPlugin/Win64/my_x64.dll"));
#endif
#endif


	// Add on the relative location of the third party dll and load it
	FString DllLibraryPath;
#if PLATFORM_WINDOWS
#if PLATFORM_64BITS
	
	//DllLibraryPath = FPaths::Combine(*BaseDir, TEXT("Binaries/ThirdParty/MyPlugin/Win64/my.dll"));
#else
	//DllLibraryPath = FPaths::Combine(*BaseDir, TEXT("Binaries/ThirdParty/MyPlugin/Win64/my.dll"));
#endif
#endif

	DllHandle = !MSCLibraryPath.IsEmpty() ? FPlatformProcess::GetDllHandle(*MSCLibraryPath) : nullptr;

	if (DllHandle)
	{
		// Call the test function in the third party library that opens a message box
	}
	else
	{
		FMessageDialog::Open(EAppMsgType::Ok, LOCTEXT("ThirdPartyLibraryError", "Failed to load dll third party library"));
	}

#endif	
}

void MyPluginModule::ShutdownModule()
{
	if (DllHandle)
	{
		FPlatformProcess::FreeDllHandle(DllHandle);
	}
	DllHandle = nullptr;

	if (IsAvailable())
	{
		UE_LOG(LogFlytekVoiceSDK, Log, TEXT("%s"), TEXT("MyPlugin Module Shutdown"));
	}
}

下面是分享的代码http://download.csdn.net/detail/u014532636/9853272

参考:

https://blog.csdn.net/lunweiwangxi3/article/details/50468593

http://blog.csdn.net/Szu_IT_Man/article/details/58232638

http://blog.csdn.net/yangxuan0261/article/details/52098104

http://blog.csdn.net/lunweiwangxi3/article/details/48373033

加载DLL参考:

http://blog.csdn.net/baidu_27276201/article/details/75675836?locationNum=2&fps=1

https://wiki.unrealengine.com/Linking_Dlls

http://blog.csdn.net/szu_it_man/article/details/58232638#引用dll

PS:http://www.valentinkraft.de/including-the-point-cloud-library-into-unreal-tutorial/

当库出现(用“0”替换“#if/#elif”)提示时在cs里加上下面这行bEnableUndefinedIdentifierWarnings = false;

ShadowariablewarningLevel=WarningLevel.0ff;

bEnableExceptions = true;

PublicDefinitions.Add("_CRT_SECURE_NO_WARNINGS"");

包含windows库的时候加上

#include "AllowWindowsPlatformTypes.h"
...
#include "HideWindowsPlatformTypes.h"

使用PCH文件

PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PrivatePCHHeaderFile = "Private/xxxPrivatePCH.h";

判断是否为编辑器

Target.bBuildEditor

判断是否为打包

Target.Configuration == UnrealTargetConfiguration.Shipping

shipping包不加后缀

UndecoratedConfiguration = UnrealTargetConfiguration.Shipping;

cpp中判断是否是编辑器

#if WITH_EDITORONLY_DATA
#endif

 ENGINE_API void aa();

cpp中判断是否是平台

#if PLATFORM_WINDOWS
#endif

#if PLATFORM_64BITS
#endif

添加预编译

bUsePrecompiled = true;

使用PCH文件

PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;

添加插件头文件

在build.cs里PublicSystemIncludePaths.AddRange添加文件夹名,默认路径Engine/Source

添加需要运行时动态加载的Module

FModuleManager::LoadModuleChecked(TEXT("MODULE_NAME"))

使用新版本的默认设置包含修改了如下

DefaultBuildSettings = BuildSettingsVersion.V2;

PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;//忽略公共包含路径的子文件夹以减少编译器命令行的长度
hadowVariableWarningLevel = WarningLevel.Error;//将阴影变量警告视为错误
bLegacyPublicIncludePaths = false;//忽略公共包含路径的子文件夹以减少编译器命令行的长度

模块参考:https://imzlp.me/posts/16643/

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
UE4中添加第三方库可以通过以下步骤实现: 1. 下载所需的库文件,通常是一个包含头文件和库文件的压缩包。 2. 解压缩该压缩包,将头文件和库文件分别复制到您的UE4项目中的合适位置。头文件一般放在项目的“Source”文件夹下的“Public”或“Private”文件夹中,库文件一般放在项目的“Binaries”文件夹下的“Win64”文件夹中(如果您的项目是64位的)。 3. 打开UE4编辑器,点击“编辑”菜单,选择“项目设置”(Project Settings)。 4. 在项目设置窗口中,选择“C++”部分,然后在“常规”(General)标签页中,找到“附加包含目录”(Additional Include Directories)选项。在该选项中添加您刚才复制的头文件所在文件夹的路径,多个路径之间用分号隔开。 5. 在同一窗口中,找到“附加库目录”(Additional Library Directories)选项。在该选项中添加您刚才复制的库文件所在文件夹的路径,多个路径之间用分号隔开。 6. 最后,在项目设置窗口中找到“链接器”(Linker)部分,在“输入”(Input)标签页中,找到“附加依赖项”(Additional Dependencies)选项。在该选项中添加您想要链接的库文件名(不包括扩展名),多个库文件之间用空格隔开。例如,如果您想链接名为“mylib.lib”的库文件,那么您应该在该选项中添加“mylib”。 7. 保存并关闭项目设置窗口,重新编译您的项目即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值