• entries
46
30
• views
51212

# Using C# Managed DLL's in UDK (or exposing managed dlls in an unmanaged application)

Followers 0

7627 views

Hello everyone,

Today I would like to share a technique I researched in order to allow DLL files created in C# to be used in the Unreal Development Kit. I posted a very similar tutorial to the one I am going to post today on my blog on the UDK forums, however since not everyone frequents that site I will post a more detailed version here for the GameDev community.

Note: The steps outlined here might be a bit advanced if you are just starting out. If you get stuck feel free to ask questions, however you may also wish to learn more about what you are doing before attempting this.

The problem

So you want to use the DLLBind feature of UDK in order to add capabilities that you need for your particular project. However what if you are not a C guru or are more comfortable with using a managed language? Well you could say "I will simply create my DLL in C#!" however that will prove problematic as the C# dll will be using managed code which is far different from an unmanaged DLL (managed code is not a direct binary file but gets turned into IL and then there are issues with export tables and all sorts of other fun technical bits that you can read in a number of much better worded articles).

Possible solutions

If we had access to the C++ code of UDK we could use various schemes to interopt with our DLL like PInvoke or Com interop, however we are stuck with the DLLBind mechanism that UDK provides to us. We need to work within the confines of what it expects and so we are left with a few options.

The first is to write two DLL files. One that is our managed DLL and then write a C/C++ wrapper DLL that allows it to interact with DLLBind. This solution is a big pain because then we are forced to use C/C++ anyway! It makes writing the DLL in C# very unappetizing.

The second is to dissemble the DLL into IL code and manually add a VTable/VTable Fixups. This is possible but a ton of work and can be a bit nerve racking (for instance now you must learn IL and hope you don't screw something up).

The third (and the option I will present in this tutorial) is to use a template to allow unmanaged DLL exports from C# (using an MSBuild task that automates a lot of the work for us).

Unmanaged Exports Template

The very first step that we will need to do is to acquire the Unmanaged Exports Template from Robert Giesecek. His template will automate a lot of the work necessary for allowing our C# dll to be used in UDK. Essentially it will provide unmanaged exports that we can then call in DLLBind!

Follow the steps the site outlines to install the template. It just took putting the entire zip file in the ProjectTemplates directory. One thing that sort of tripped me up is that you locate the required folders through the My Documents folder and not Program Files (I guess I should have read it a bit more carefully!)

Then we can create a project based off of his template.

A Simple Example

I started with a very simple test DLL to test the capabilities of the approach. Here is the C# code I used:

using System;using System.Runtime.InteropServices;using System.Collections.Generic;using System.Text;using RGiesecke.DllExport;namespace UDKManagedTestDLL{ internal static class UnmanagedExports { [DllExport("GetGreeting", CallingConvention = CallingConvention.StdCall] [return: MarshalAs(UnmanagedType.LPWStr)] static String GetGreeting() { return "Happy Managed Coding!"; } }}

I compiled this DLL and put it in the User Code folder. I am using Windows XP so I built my DLL as a 32 bit dll, however if you are running a 64 bit operating system then you will want to change the steps appropriately. The MarshalAs is a way to tell C# how to marshal the return string to the unmanaged code. This allows us to control how the managed types are transfered to the unmanaged types of UDK.

Then I created a class in UnrealScript (Which was named TestManagedDll.uc (which should be obvious as that is the class name, but I thought I would point it out).
) that contained the following:

class TestManagedDLL extends Object DLLBind(UDKManagedTestDLL);dllimport final function string GetGreeting();DefaultProperties{}

Which I could call from my cheat manager like:

exec function testdll(){ local TestManagedDLL dllTest; local PlayerController PC; dllTest = new class'PFGame.TestManagedDLL'; foreach WorldInfo.AllControllers(class'PlayerController',PC) { PC.ClientMessage(dllTest.GetGreeting()); }}

So then I ran it and saw in my results:

Passing Parameters

Right then we also would like the ability to pass parameters and we can do that like so:

 [DllExport("GetGreetingName", CallingConvention = CallingConvention.StdCalll)] [return: MarshalAs(UnmanagedType.LPWStr)] static String GetGreetingName([MarshalAs(UnmanagedType.LPWStr)] String name) { return "Happy Managed Coding " + name + "!"; }

With:

dllimport final function string GetGreetingName(string name);

and

exec function testdll(string greetName){ local TestManagedDLL dllTest; local PlayerController PC; dllTest = new class'PFGame.TestManagedDLL'; foreach WorldInfo.AllControllers(class'PlayerController',PC) { PC.ClientMessage(dllTest.GetGreetingName(greetName)); }}

produces:

I assume a lot of people will want to use this technique to write C# DLL's that use .NET for working with files, since the UDK support for reading various file formats is so low. In order to do that we need to get the directory that the DLL is in, so that we can locate our files appropriately. We can do this using Reflection.

 public static String GetAssemblyPath() { string codeBase = Assembly.GetExecutingAssembly().CodeBase; UriBuilder uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); return Path.GetDirectoryName(path); } [DllExport("ReadTxtFile", CallingConvention = CallingConvention.StdCall)] [return: MarshalAs(UnmanagedType.LPWStr)] static String ReadTxtFile([MarshalAs(UnmanagedType.LPWStr)] String name) { string retVal = ""; StreamReader test = null; try { test = new StreamReader(Path.Combine(GetAssemblyPath(), name)); retVal = test.ReadToEnd(); } catch (Exception ex) { retVal = ex.Message; } finally { if (test != null) { test.Close(); } } return retVal; } }

You should then be able to put a file in the same folder as the dll and then load it up and get the contents.

It also needs:
using System.IO;using System.Reflection;

So it should be perfectly possible with some rudimentary knowledge to make dlls that make use of XML, files, ect.

Returning and Passing structures

NOTE: The following content may or may not be the best way to approach this problem. I will share what I have so far as a starting point, however you may wish to investigate this matter further. The use of IntPtr can be error prone and buggy but sometimes custom marshalling is the only way to solve particular problem domains when doing this sort of work. I have done some use of using "ref" and letting it handle this sort of marshaling for me, however it does not appear to work in all circumstances.

 private static IntPtr MarshalToPointer(object data) { IntPtr buf = Marshal.AllocHGlobal( Marshal.SizeOf(data)); Marshal.StructureToPtr(data, buf, false); return buf; } struct MyVector { public float x, y, z; } [DllExport("ReturnStruct", CallingConvention = CallingConvention.StdCall)] static IntPtr ReturnStruct() { MyVector v = new MyVector(); v.x = 0.45f; v.y = 0.56f; v.z = 0.24f; IntPtr lpstruct = MarshalToPointer(v); return lpstruct; }

where:

dllimport final function vector ReturnStruct();

and:

exec function testdll(){ local TestManagedDLL dllTest; local PlayerController PC; local Vector v; dllTest = new class'PFGame.TestManagedDLL'; foreach WorldInfo.AllControllers(class'PlayerController',PC) { v = dllTest.ReturnStruct(); PC.ClientMessage(v.Y); }}

we get:

The other direction is also possible:

 private static object MarshalToStruct(IntPtr buf, Type t) { return Marshal.PtrToStructure(buf, t); } [DllExport("SumVector", CallingConvention = CallingConvention.StdCall)] static float SumVector(IntPtr vec) { MyVector v = (MyVector)MarshalToStruct(vec, typeof(MyVector)); return v.x+v.y+v.z; }

with:

dllimport final function float SumVector(Vector vec);

and:

exec function testdll(){ local TestManagedDLL dllTest; local PlayerController PC; local Vector v; v.X = 2; v.Y = 3; v.Z = 5; dllTest = new class'PFGame.TestManagedDLL'; foreach WorldInfo.AllControllers(class'PlayerController',PC) { PC.ClientMessage(dllTest.SumVector(v)); }}

(outputs 10).

When passing a structure as an out parameter you can do the following, however I have not been able to get the whole strings inside structs thing to work without crashing and if someone figures out how, that would be an awesome addition to this. I am willing to bet the problem is nested structs are not being marshaled correctly and you will need to do a custom marshaling to get it to work properly (which means using IntPtr and other magic).

 struct TestStruct { public int val; } [DllExport("OutTestStruct", CallingConvention = CallingConvention.StdCall)] static void OutTestStruct(ref TestStruct testStruct) { testStruct.val = 7; }

with:

dllimport final function OutTestStruct(out TestStruct test);

and your struct defined in UnrealScript like:

struct TestStruct{ var int val;};

FINAL NOTE: This method may have serious drawbacks and limitations. One huge problem is that you risk leaking memory like the titanic. I am not sure how well everything is getting freed... I urge caution. I am merely providing a technical basis but it will be up to you to assume the risks of the implementation for your particular project. I take no responsibility for the use or misuse of this information for any reason whatsoever.

References:

Mastering Structs in C#
Getting Assembly Path

I hope this provides someone some assistance!

5
Followers 0

I've been thinkering with the UDK a little bit and this will definitely come in handy. Thanks a lot!
0

Might I suggest for MarshalToStruct:

[code]
private static T MarshalToStruct<T>(IntPtr buf)
{
return (T)Marshal.PtrToStructure(buf, typeof(T));
}
[/code]

Stronger typing for the win, and less code, too.
2

[quote name='coldacid' timestamp='1311250597']
Might I suggest for MarshalToStruct:

[code]
private static T MarshalToStruct<T>(IntPtr buf)
{
return (T)Marshal.PtrToStructure(buf, typeof(T));
}
[/code]

Stronger typing for the win, and less code, too.
[/quote]

Thank you for the suggestion, it does look like a cleaner way to do things! I simply reused the MarshalToStruct function that I encountered in my linked article and did not give much thought to it.
0

Hey, thanks for the great tutorials.

I am using dll's in my game too but I have a problem. When I cook the build using Unreal Frontend it is not included in cooked version.

Any thoughts?

Regards,

0

## Create an account

Register a new account

• 27
• 12
• 11
• 31
• 20