• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
  • entries
    46
  • comments
    30
  • views
    51212

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

Sign in to follow this  
Followers 0
shadowisadog

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:

managedlltest.jpg

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:

managedlltest2.jpg

Reading Files

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:

managedlltest3.jpg

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
Sign in to follow this  
Followers 0


4 Comments


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

Share this comment


Link to comment
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

Share this comment


Link to comment
[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

Share this comment


Link to comment

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,

Madhu.

0

Share this comment


Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now