UE动态链接库使用方法

发布时间 2023-09-08 10:49:18作者: hanabc12345

本方法UE5,VS studio2022

一.VS studio2022创建一个动态库:命名myDll1

1.在头文件中新建TesLlib.h

#pragma once
#define DLL_API _declspec(dllexport)
 class DLL_API TesLlib
{
public:
    int Add(int a, int b);
};

在源文件中新建TesLlib.cpp

#include "pch.h"
#include "TesLlib.h"
int TesLlib::Add(int a, int b)
{
    return a + b;
}

2.编译成功后,其中有三个文件很重要,分别是TesLlib.h,myDll1.lib,myDll1.dll

..myDll1\x64\Debug文件下有.lib,.dll

...\myDll1\myDll1文件下有.h

拷贝这三个文件后面要用。

二.新建一个UE C++项目,成功后

1.将.dll拷贝到项目的..\Binaries\Win64文件夹下

2.在..\Source\myDllTest文件夹下新建ThirdParty文件夹,再新建include和lib文件夹

3.分别将.h放入include中,将.lib放入lib中,然后更新项目打开C++文件,可以在目录中看到ThirdParty文件内容

4.在..\Source\myDllTest文件下有myDllTest.Build.cs打开文件写入代码

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

using UnrealBuildTool;
using System.IO;

public class myDllTest : ModuleRules
{
    private string ModulePath 
    {
        get
        {
            return ModuleDirectory;
        }             
    }
    private string ThirdPartyPath
    {
        get
        {
            return Path.GetFullPath(Path.Combine(ModulePath,"ThirdParty"));
        }
    }

    public myDllTest(ReadOnlyTargetRules Target) : base(Target)
    {
        PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
    
        PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" });

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

        // Uncomment if you are using Slate UI
        // PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });

        // Uncomment if you are using online features
        // PrivateDependencyModuleNames.Add("OnlineSubsystem");
        PublicIncludePaths.Add(Path.Combine(ThirdPartyPath, "include"));
        PublicAdditionalLibraries.Add(Path.Combine(ThirdPartyPath, "lib", "myDll1.lib"));
        // To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
    }
}

红色为新加入的代码。然后编译,成功!

5.在UE中新建C++类继承蓝图函数库,打开代码在.h文件中写入代码

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

/**
 * 
 */
UCLASS()
class MYDLLTEST_API UMyBlueprintFL1 : public UBlueprintFunctionLibrary
{
    GENERATED_BODY()

public:
    UFUNCTION(BlueprintCallable,Category="My Library")
    static int BFL_Add(int a,int b);
    
};

红色为新加入的代码。在.cpp中写入代码

#include "MyBlueprintFL1.h"
#include "ThirdParty/include/TesLlib.h"


int UMyBlueprintFL1::BFL_Add(int a, int b)
{
    TesLlib* testlib = new TesLlib();
    int result = testlib->Add(a, b);
    delete testlib;
    return result;
}

然后编译,成功后打开UE蓝图

6.在关卡蓝图中,写入

点击运行,成功显示结果。表示成功

三.参考文献

1.【详细全流程】UE4调用第三方库 动态链接库 dll C++_ue4 第三方库_虚数魔方的博客-CSDN博客

2.【UE5】UE项目中静态库还没整明白吧,动态链接库又来了_哔哩哔哩_bilibili