本人在写这篇文章时候,网上已经有很多相关的文章,但是网上的文章缺少逐步指引,本人看的云里雾里,估计刚接触相关工作的人看的也不是很清楚。本着自己记录和让他人少踩一些坑的宗旨------这篇文章诞生了。好了,不多BB,直接进入主题。
创建自定义dll动态链接库
首先新建一个动态链接库的C++项目:
然后在项目里添加C++类:DllClass,内容如下:
//.h
#define DLL_EXPORT __declspec(dllexport)
#define PI 3.1415926
#ifdef __cplusplus
extern "C"
{
#endif
float DLL_EXPORT getCircleArea(float radius);
#ifdef __cplusplus
}
#endif
其中这几句是必须的,其他的可以省略掉,其他内容的意思是以C语言的方式编译这段代码,可以根据项目需要添加或删除
//.h
//要导出的函数必须要加__declspec(dllexport)前缀,此处声明DLL_EXPORT代替这个略显繁琐的前缀
#define DLL_EXPORT __declspec(dllexport);
//定义π
#define PI 3.1415927
//要导出的函数(求圆的面积)
float DLL_EXPORT getCircleArea(float radius);
cpp没什么可看的,实现了一个非常简单的一个求圆的面积的函数
//.cpp
#include "pch.h"
#include <math.h>
#include "dllClass.h"
float DLL_EXPORT getCircleArea(float radius)
{
return (PI * pow(radius,2));
}
然后选择x64 Release开始编译:
这里注意不要傻乎乎选择x86,因为UE4是x64 Orz
编译成功后会在项目目录的 x64\Release 下看到已经生成成功dll文件了。
加载自定义dll动态链接库
首先创建一个ue4 c++的项目,相信这一步就不用我详细介绍了吧~
创建DLL的文件夹,和Content同级:
把上一步生成的dll文件拷贝到里面:
然后新建一个C++类用于加载和使用dll文件,选择继承:BlueprintFunctionLibrary
C++类里添加函数:
//.h
UFUNCTION(BlueprintCallable, Category = "GZW|DLL")
static float getCircleArea(float radius);
//.cpp
//求圆面积的函数指针
typedef float (*_getCircleArea) (float radius);
float MyBlueprintFunctionLibrary::getCircleArea(float radius)
{
//dll文件路径
FString filePath = FPaths::Combine(*FPaths::ProjectDir(), TEXT("DLL/"), TEXT("GzwDll.dll")); // Concatenate the plugins folder and the DLL file.
if (FPaths::FileExists(filePath)) //Can the file be found?
{
void* DLLHandle;
DLLHandle = FPlatformProcess::GetDllHandle(*filePath);
if (DLLHandle != NULL)
{
_getCircleArea DLLgetCircleArea = NULL;
//DLL中定义的函数的名称
FString procName = "getCircleArea"; //The name of the function defined in the DLL
DLLgetCircleArea = (_getCircleArea)FPlatformProcess::GetDllExport(DLLHandle, *procName); // Export the DLL function.
if (DLLgetCircleArea != NULL)
{
float out = DLLgetCircleArea(radius); // Call the DLL function, with arguments corresponding to the signature and return type of the function.
return out; // return to UE
}
}
}
else
{
GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Green, TEXT("Dll file not found !!!"));
}
return 1.00f;
}
随便创建个蓝图放到世界里,圆的半径设置为3.0:
可以看到屏幕正确输出了圆的面积:
把自定义Dll封装成插件供UE引擎使用
待更新~~