当前位置: 首页 > article >正文

UE5以插件的形式加载第三方库

之前在UE中加载第三方库的形式是以静态或者动态链接的形式加载但是不太容易复用。就想着能不能以插件的形式加载第三方库,这样直接把插件打包发行就可以复用了,之前也找过相应的教程但是很难找到比较简单易懂的教程,要么是比较复杂,要么是自己跟着教程做了一遍但是打包插件的时候,打包不成功。自己在经过各种查找教程及自己总结,发现了一种感觉相对比较简单的方法,下面把整体的过程介绍一下。
1 先创建一个C++的UE 项目,在项目中创建一个空白的插件,可以使用不同的UE版本,博主使用的是UE5.5 如下图
在这里插入图片描述
在这里插入图片描述
在MyPlugin下新建 ThirdParty文件夹,在ThirdParty文件下新建
include,lib,Win64文件夹,在include文件夹下放需要调用的第三放库的.h文件,在lib文件下放相应的.lib文件,Win64下放相应的.dll 文件。我这里用的 pch.h Wll_Dll.lib Wll_Dll.dll (创建第三库的方法之前写过,这里不再赘述)
在这里插入图片描述
2 下面开始设置MyPlugin.Build.cs的设置,整体的代码如下

// Copyright Epic Games, Inc. All Rights Reserved.

using System.IO;
using UnrealBuildTool;

public class MyPlugin : ModuleRules
{
	public MyPlugin(ReadOnlyTargetRules Target) : base(Target)
	{
        // 使用共享 PCH,减少编译时间
        PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;

        // 添加依赖模块,确保 UHT 正确生成代码
        PublicDependencyModuleNames.AddRange(new string[] {
            "Core",
            "CoreUObject",
            "Engine"
        });

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

        // 获取插件目录路径
        string PluginPath = ModuleDirectory;
        string ThirdPartyPath = Path.Combine(PluginPath, "../../ThirdParty");


        // 确保 DLL 在打包时会被复制到 Binaries/Win64
        if (Target.Platform == UnrealTargetPlatform.Win64)
        {
            string DLLPath = Path.Combine(ThirdPartyPath, "Win64", "Wll_Dll.dll");

            // 添加运行时依赖,确保 DLL 被复制到 Binaries 目录
            RuntimeDependencies.Add("$(PluginDir)/Binaries/Win64/Wll_Dll.dll", DLLPath, StagedFileType.NonUFS);
        }
    }
}

在运行时加载.DLL 关闭时卸载,MyPlugin.h的代码如下

#pragma once

#include "Modules/ModuleManager.h"
// DLL 句柄和函数指针
void* DLLHandle = nullptr;
typedef int (*AddNumbersFunc)(int, int);
AddNumbersFunc AddNumbersPtr = nullptr;
class FMyPluginModule : public IModuleInterface
{
public:

	/** IModuleInterface implementation */
	virtual void StartupModule() override;
	virtual void ShutdownModule() override;
};

MyPlugin.cpp 的代码如下

// Copyright Epic Games, Inc. All Rights Reserved.

#include "MyPlugin.h"
#include "Misc/Paths.h"
#include "HAL/PlatformProcess.h"
#define LOCTEXT_NAMESPACE "FMyPluginModule"

void FMyPluginModule::StartupModule()
{
    // This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module
    FString DLLPath = FPaths::Combine(FPaths::ProjectPluginsDir(), TEXT("MyPlugin/Binaries/Win64/Wll_Dll.dll"));
    UE_LOG(LogTemp, Warning, TEXT("Trying to load DLL from path: %s"), *DLLPath);

    if (!FPaths::FileExists(DLLPath))
    {
        UE_LOG(LogTemp, Error, TEXT("DLL not found at: %s"), *DLLPath);
        return;
    }

    // 加载 DLL
    DLLHandle = FPlatformProcess::GetDllHandle(*DLLPath);
    if (!DLLHandle)
    {

        UE_LOG(LogTemp, Error, TEXT("Failed to load DLL: %s"), *DLLPath);
        return;
    }

    // 绑定 DLL 函数
    AddNumbersPtr = (AddNumbersFunc)FPlatformProcess::GetDllExport(DLLHandle, TEXT("Add"));//Dll 的两个导出函数 名 分别是 Add,Log
    if (!AddNumbersPtr)
    {
        UE_LOG(LogTemp, Error, TEXT("Failed to bind AddNumbers function from DLL"));
    }
    else
    {
        UE_LOG(LogTemp, Warning, TEXT("AddNumbers function bound successfully"));
    }
}

void FMyPluginModule::ShutdownModule()
{
	// This function may be called during shutdown to clean up your module.  For modules that support dynamic reloading,
	// we call this function before unloading the module.
    if (DLLHandle)
    {
        FPlatformProcess::FreeDllHandle(DLLHandle);
        DLLHandle = nullptr;
        UE_LOG(LogTemp, Warning, TEXT("DLL Unloaded Successfully."));
    }
}

#undef LOCTEXT_NAMESPACE
	
IMPLEMENT_MODULE(FMyPluginModule, MyPlugin)

创建c++的蓝图函数库如下,在蓝图库函数中创建调用函数并暴露给蓝图使用
在这里插入图片描述
MyBlueprintFunctionLibrary.h 的代码如下

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "MyBlueprintFunctionLibrary.generated.h"

/**
 * 
 */
UCLASS()
class MYPLUGIN_API UMyBlueprintFunctionLibrary : public UBlueprintFunctionLibrary
{
	GENERATED_BODY()
public:
    UFUNCTION(BlueprintCallable, Category = "MyPlugin")
    static int CallAddNumbers(int A, int B);
};

MyBlueprintFunctionLibrary.cpp的代码如下

 if (AddNumbersPtr)
 {
     return AddNumbersPtr(A, B); // 调用 DLL 中的函数
 }
 else
 {
     UE_LOG(LogTemp, Error, TEXT("AddNumbersPtr is NULL!"));
     return -1; // 如果函数指针为空,返回错误
 }

以上就是整体的创建流程及完整的运行代码,下面贴上运行结果
在这里插入图片描述
在这里插入图片描述
现在打包还是不能够成功的,得在MyPlugin.uplugin 加上白名单
代码 “WhitelistPlatforms”: [“Win64”] 完整的MyPlugin.uplugin 代码如下

{
	"FileVersion": 3,
	"Version": 1,
	"VersionName": "1.0",
	"FriendlyName": "MyPlugin",
	"Description": "",
	"Category": "Other",
	"CreatedBy": "",
	"CreatedByURL": "",
	"DocsURL": "",
	"MarketplaceURL": "",
	"SupportURL": "",
	"CanContainContent": true,
	"IsBetaVersion": false,
	"IsExperimentalVersion": false,
	"Installed": false,
	"Modules": [
		{
			"Name": "MyPlugin",
			"Type": "Runtime",
			"LoadingPhase": "Default",
			"WhitelistPlatforms": [
				"Win64"
			]
		}
	]
}

加上后就可以打包插件了,也可以给别人使用你这个插件,好了本片文章到此结束,还要把ThirdParty 文件夹复制到打包好的插件中。


http://www.kler.cn/a/582722.html

相关文章:

  • 科技工作者之家建设扬帆起航,为科技人才提供更多优质服务
  • Web服务器配置、虚拟主机配置、访问权限控制
  • 无人机+无人车+机器狼+DeepSeek:智能化设备集群技术详解
  • 【docker】Windows10启动Docker Desktop - WSL update failed
  • 安装 ubuntu 2404 LTS 服务器 设置 服务器名称
  • JVM的垃圾回收器都有哪些?
  • Vite打包原理: Tree-shaking在Vue3项目中的实际效果
  • JVM垃圾收集器合集
  • 查看linux系统重启的日志
  • 利用8个参数定义一个汽轮机,然后根据这8个参数生成汽轮机性能试验时的测点清单-pycharm-源代码(适用所有类型汽轮机)
  • 数智读书笔记系列016 从《理解和改变世界》探寻AI时代的知识与智能密码
  • 邮箱验证:外贸邮件营销中的关键策略
  • 在终端中用code命令打开vscode并加载当前目录了
  • 部署项目至服务器:响应时间太长,无法访问此页面?
  • AGI大模型(2):GPT:Generative Pre-trained Transformer
  • 【C++ STL】 容器详解:pair 学习
  • electron + vue3 + vite 渲染进程与渲染进程之间的消息端口通信
  • 力扣:3305.元音辅音字符串计数
  • 根据 GPU 型号安装指定 CUDA 版本的详细步骤(附有CUDA版本对应torch版本的表格)
  • 神经网络探秘:原理、架构与实战案例