ReflectionUtil

August 14, 2012

Hi.

Due to recent comments i realized i never put up a class called ReflectionUtil which is being used by the sample source code for a lua engine

So here it is.

Thue

Embedding Lua in C# .Net – Part III

February 21, 2011

This post contains a full managed lua wrapper around the lua API, a simple script engine making life easier when communicating with lua, a sample class ‘NPCPlayer’ to integrate with lua, a sample program using the script engine and the sample class and last a basic explanation of the lua stack.

Hopefully the post will fill in the gaps from part I and II and I will provide all the working source code to illustrate lua embedding.

Source code
All files referenced in this post can be downloaded as a zip file found here.
The source code contains lots of useful comments as well.

A full managed lua wrapper
The managed wrapper is defined in its completeness in the static class ‘Lua’
This class wraps all the lua c functions and constants, and bridges the integration to the natively compiled lua.dll.

The wrapper class can be found in the zip file in the introduction of the post.

A simple Script engine – how to use the managed wrapper
The wrapper is basically just a 1-1 bridging of the full lua API and constants.
To use it you will therefore need to understand how the various lua API functions work.

Most of the functions exposed through lua API operate on the lua stack.
To make life easier in communicating with lua through the stack, I have made a simple script engine class that has methods that encapsulates the lua API calls for some of the things you’ll often have to do.

This includes:

  • Instantiating lua and managing the lua state.
  • Error logging with messages from lua interpreter
  • Registering C# methods with lua
  • Creating a lua table
  • Getting and setting table fields
  • Pushing and popping values on the lua stack
  • Running a script file

The script engine class can be found in the zip file in the introduction of the post.

Demonstration application
I have made a small console app to demonstrate the use of the scriptengine together with a sample class ‘NPCPlayer’.
The app consists of a single class ‘Program’ in a single file.

The demonstration program class and the NPCPlayer class can be found in the zip file in the introduction of the post.

The lua stack
 
The single most important thing when extending your application with lua is to understand how the lua stack works, and how exactly you use it to communicate with lua.

Stack data structure
A stack data structure is a general structure used in many different languages to solve various computing problems.
If you do not know yet what a stack structure is and how it works, you should start by looking at an explanation here.

As you can see a stack data structure is kind of a tower of data elements stacked on top off each other.
When a new data element is put on top of the stack it is called a PUSH operation.
When the top element of the stack is removed, it is called a POP operation. 

PUSH and POP always operate from the top of the stack.
The stack is also called a LIFO structure (last in first out) because of how the operations on the stack function. 

An example
As a starting example I will explain the lua API function calls used in the script engines method ‘CreateLuaTable’
The lua stack will be empty after opening lua, and the ‘CreateLuaTable’ assumes an empty stack as well.

The method looks like this and takes a single string parameter containing the name of a lua table to create in lua.

public void CreateLuaTable(string tableName)
{
            Lua.lua_getglobal(m_lua_State, tableName);

            if (IsTopNil)
            {
                //remove the nil value
                Lua.lua_pop(m_lua_State, 1);
                Lua.lua_newtable(m_lua_State);
                Lua.lua_setglobal(m_lua_State, tableName);
                //stack is empty
            }
            else
            {
                //remove the existing table from the stack
                Lua.lua_pop(m_lua_State, 1);
            }
}

Explanation
First I use lua_getglobal to check if the table already exists.
Lua_getglobal PUSHES the lua table onto the lua stack if the table did exist, else it will leave the stack with a nil value on top.

I then check if the top of the lua stack is nil, if it is the table did not exist and I will create it.
I POP the nil value off the stack with lua_pop, that takes as argument how many elements to pop.

Stack is now again empty.

I then create a new lua table with lua_newtable which PUSHES the new lua table object onto the stack

A single table element is now sitting on top of the stack.

Then I set the name of the new table by using lua_setglobal which POPS the top element from the stack (must be a table element), while associating the identifier with it.

Stack is now again empty.

If at first the table did already exists, I make sure to balance the stack again properly in the else clause, by POPPING the found table object off the stack.
Either way the stack will look exactly as it did before entering the method.

This is the easiest way to ensure proper stack use.
There can be times though when it’s fitting to leave a table object on top of the stack when performing multiple operations on the same table, instead of constantly PUSHING and POPPING it on and off the stack.

It’s critical to know exactly how each lua API function will treat the stack when it is called.
How many arguments and their types will it assume on the stack when called?
How many elements will be left on the stack when the function is done?

You will have to look this behavior up in the lua documentation, until you get familiar with it.

Conclusion 
This ends part III of Embedding Lua in C# .Net
I hope you will find the post and the code snippets useful.

Thue Tuxen

Crackme introduction and starting points

March 15, 2010

Wikipedia definition snippet
A crackme (often abbreviated by cm) is a small program designed to test a programmers reverse engineering skills.
They are programmed by other reversers to have a legal way to “crack” software.
http://en.wikipedia.org/wiki/Crackme 

Introductory keyGenme
For me crackmes are a hobby in which I, in a legal way, sharpen my knowledge about writing secure code and discover techniques to protect software against reversing/cracking.
Practicing in this area also enables you to dive into undocumented API´s and unknown file formats and gives you a great understanding about the attack vectors and pitfalls of writing secure software.
It’s like solving a puzzle although more fun, as I by no means find it good entertainment to assemble 10.000 pieces of Niagara falls :o) 

I’ve created an introductory keyGenme for you to tamper with.
You can get it from http://www.tuxenconsulting.dk/tUx.zip 

Rules are included in the zip file, no patching (only for practice reasons :), make a keygen.
The keygen should be able to create valid serials given a username. 

Embedded music is composed on C64 SID chip hope you like it, cant remember where credit goes but i had no part in creating it.

  

Where to begin
In this introduction I want to give you some starting points to information and tools to get going.
Solving crackmes is all about reading about the inner workings of stuff and when you have read a lot, then read some more,
as there’s really no end in what to discover as a lot of very talented people has contributed lots of creative information and techniques over time. 

You will need a lot of different tools and one or several good debuggers, for most crackmes a user-mode debugger will suffice.  

Masm32.com
This site is a good starting place for getting an assembler IDE and some tutotials.
As the name implies it uses a version of Microsofts Macro Assembler in its distribution.
It comes with a lot of helpful macros and its own runtime library to help you get things done.

OllyDbg
This is a free debugger and its very cool, you should register when downloading.
It’s very convenient and has many great features.
Version 2.0 is in final beta so I recommend you use that instead of earlier versions.

Get it at http://www.ollydbg.de

Key features are:

  • Code analyzer – generates assembly listings and recognizes more than 1900 standard API and 400 C functions
  • Possibility to patch memory in real time and write the modified exe back to disk when you’re happy with your changes.
  • Nice memory search facilities
  • Cool GUI interface where you simultaneously can watch chosen parts of memory, the stack, where you’re at code wise, register and flags,
    loaded module, import/export tables for each module and much more.
  • It’s possible to write plugins for OllyDbg to extend functionality

Intel
Intel’s documentation in regards to instruction set/design/opcodes is necessary.
http://www.intel.com/products/processor/manuals/
 
Watch for
Intel® 64 and IA-32 Architectures Software Developer’s Manual Volume 2A: Instruction Set Reference, A-M
Intel® 64 and IA-32 Architectures Software Developer’s Manual Volume 2B: Instruction Set Reference, N-Z
 
Microsoft
It’s necessary to know how Portable executable (PE .exe) files are structured.
http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx

If you have Visual studio, there’s some nice tools to be found within the installation.
Dumpbin.exe is good for initial analyzing for having a look at sections, headers, import/exports, symbols etc.
Depends.exe is great for walking the module dependencies of an executable.
Undname.exe, undecorate c++ symbol names.

 
Books
Best recommendations goes to this book about assembly programming by Kip R. Irvine, it’s invaluable if you want to get anywhere:
http://www.amazon.co.uk/Assembly-Language-Intel-Based-Computers-Irvine/dp/0136603904/ref=sr_1_12?ie=UTF8&s=books&qid=1268502985&sr=1-12

A new updated version is coming out soon, should be worth getting too:
http://www.amazon.co.uk/Assembly-Language-X86-Processors-Irvine/dp/013602212X/ref=sr_1_5?ie=UTF8&s=books&qid=1268502985&sr=1-5
 
And this book about windows programming with c/c++ is great on many aspects of working in the windows environment:
http://www.amazon.co.uk/Windows-PRO-Developer-Jeffrey-Wintellect-Christophe/dp/0735624240/ref=sr_1_1?ie=UTF8&s=books&qid=1268504901&sr=1-1

Crackmes.de
I can recommend this site as a good starting site.
You can download a lot of available crackmes, keygenmes, reversemes etc. rated by difficulty.
Quite a bit of learning can be obtained from going through some of the posted solutions.

Search search search
Wikipedia and google should be used extensively, a lot of information is shared out there, containing great stuff on this and that, and it’s all free for you to read, and you should.
Just  remember to use your sanity filter on what you read and where you go to read it (beware of malicious sites), and always scan any downloaded crackmes.

Search terms you should dive into:
Stack, calling convention, packer / unpacker, stream cipher, portable executable format, virtual memory, windows API, windows program layout, little-endian / big-endian, usermode / kernel mode debugger, reverse engineering, anti debugger techniques, anti reversing

Hope you find any of the information provided useful.
Happy reversing.

Thue Tuxen

Embedding Lua in C# .Net – Part II

January 7, 2010

Using Lua with .Net C# part II 

In the previous post I showed how the Lua source code can be built for use by .Net, and how to make a very simple hello Lua script, and execute it from .Net code. 

Putting Lua to real use 
To actually do something interesting Lua must be able to call into .Net functions that is registered with Lua. 

 This enables all sorts of exciting features, such as exposing your business / game objects to Lua and create Lua scripts for AI, custom business processing etc. 

.Net function signature for Lua callbacks 
Every .Net function that Lua should be able to call must match a specific function signature, and must also be registered with Lua. 

This is how the function signature should look in .Net: 

/*  definition from lua.h source code file
 *  typedef int (*lua_CFunction) (lua_State *L);
 */
public delegate int LuaFunction(IntPtr lua_State);

Every .Net function exposed to Lua must return an int and takes a pointer to the Lua state as its single argument. 

The Lua state object is used to get the parameters for the function along with any other variable values you need for your logic to work. 

Communicating with Lua and the Lua stack 
You do not operate on the Lua state itself, instead you call Lua C library functions which all takes the Lua state as parameter. 

Lua uses a stack for all communication from .Net to Lua (and from any other language to Lua)If you want to create a new object in Lua (called a Lua table) you use the stack available from the Lua state to create it and set values of any desired fields. 

In short, you will need wrapper functions in .Net to operate on the Lua stack, and Lua exports a whole bunch of functions that operates on this stack, which I will show later. 

A complete guide for the lua stack can be found in the Lua documentation, section 3 at http://www.lua.org/manual/5.1/manual.html 

Lua wrappers and the Lua.h source code file
Lua has an API function for registering a function from another language, its quite simple and when wrapped in .Net I created one that looks like this:

public void RegisterLuaFunction(Lua.LuaFunction func, string luaFuncName)
{
   //call the lua_register API function to register a .Net function with
   //the name luaFuncName and a function pointer func
   //the function pointer is defined using the delegate shown earlier
   //when making the correct Lua function signature for .Net functions
   Lua.lua_register(m_lua_State, luaFuncName, func);

   //make sure the delegate callback is not collected by the garbage collector before
   //unmanaged code has called back
   m_refs.Add(func);
}

Dont worry too much about the m_refs.Add(func); call. 
When I first started out creating a Lua wrapper I learned the hard way (debugging debugging debugging) that .Net garbage collects delegates, in use for Lua callbacks, before I intended .Net to do so. 

When Lua calls back into .Net, the function pointer is suddenly no more valid, and a runtime exception occurs.

By maintaining a list of references to registered Lua callbacks in .Net, I make sure that the garbage collector wont collect the functions pointers before I want it to. The list Im using in my wrapper is defined as this:

private static List<Delegate> m_refs = new List<Delegate>();

When I close Lua I just empty the list of refs and they will be collected and I will be happy.
The wrapper for the register function looks like this:

//definition from lua.h source code file
//#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n)))
public static void lua_register(IntPtr lua_State, string n, LuaFunction func)
{
   lua_pushcfunction(lua_State, func);
   lua_setglobal(lua_State, n);
}

You might wonder why theres no DLLImport Attribute.
Take a look at the definition from lua.h, its actually a macro using two other Lua API functions. These two functions must be wrapped as well.
Lua uses macro definitions here and there, actually lua_pushcclosure and lua_setglobal is also just macros:

//#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0)
public static void lua_pushcfunction(IntPtr lua_State, LuaFunction func)
{
   lua_pushcclosure(lua_State, func, 0);
}

//#define lua_setglobal(L,s)     lua_setfield(L, LUA_GLOBALSINDEX, (s))
public static void lua_setglobal(IntPtr lua_State, string s)
{
   lua_setfield(lua_State, LUA_GLOBALSINDEX, s);
}

The lua_pushcclosure and lua_setfield functions is actual C API function and is lua.h defined and wrapped like this:  

//LUA_API void  (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n);
[DllImport("lua5.1.dll")]
public static extern void lua_pushcclosure(IntPtr lua_State, [MarshalAs(UnmanagedType.FunctionPtr)] LuaFunction func, int n);

//LUA_API void  (lua_setfield) (lua_State *L, int idx, const char *k);
[DllImport("lua5.1.dll")]
public static extern void lua_setfield(IntPtr lua_State, int idx, string s);

This is getting a bit boring I hope I did not lose you completely there, if I did Im sorry 🙂 
The point is to show how Lua API functions can be put in a .Net wrapper that emulates the complete Lua API. 

Registering a .Net callback funtion with Lua 
Lets imagine that we have created a game and in that game we have created a class in .Net which contains methods for manipulating a “NPC player” object. 
Now we want to be able to create combat scripts, task scripts, AI scripts etc. 

Furthermore we want users of the game to be able to create their own levels and define behaviour for NPC characters in that level. 
Most users can learn to write a Lua script and we choose to expose some functionality from the “NPC player” class. 
We fire up an instance of Lua by creating a Lua state, and then we register some .Net functions with Lua. 

Somewhere in our ScriptEngine we have defined: 

 
private static IntPtr m_lua_State = IntPtr.Zero; 

And open Lua: 

 
m_lua_State = Lua.lua_open(); 

//open Lua libraries 
Lua.luaL_openlibs(m_lua_State); 

Our NPCPlayer class definition:

 
public class NPCPlayer
{
  bool InCombat(string characterName)
  {
      //not implemented, always in combat
      return true;
  }
  int Lua_InCombat(IntPtr m_lua_State)
  {
      //get the characterName from Lua
      string cName = string.Empty;
      //if theres a sring argument on top of the stack,
      //LUA_TSTRING = 4 see lua.h
      if (lua_type(m_lua_State, -1) == 4)    
      {
          value = lua_tostring(m_lua_State, -1);
          //pop value from stack
          lua_pop(m_lua_State, 1);
          //the stack is now 'balanced',
          //we got 1 argument, we popped 1 argument
          //now return 1 argument based on the result from InCombat(string)
          //push the return value on the stack and return 1
          Lua.lua_pushboolean(m_lua_State, InCombat(cName));
          return 1;
      }
      else
      {
          //error, invalid argument or no argument on the Lua stack
          //check Lua script for errors and optionally ask Lua for an error message
          //clear the stack
          lua_settop(m_lua_State, 0);
      }
      //sigmal no return value, something went wrong
      return 0;
  }
}

None of our methods match the Lua signature so we have to create Lua ‘trampolines’ for them and handle the Lua communication specifics in them. We register a Lua function callback for the NPCPlayer class like this:

RegisterLuaFunction(new Lua.LuaFunction(Lua_InCombat), "InCombat");

Calling the registered C# method from Lua
The Lua_InCombat method can now be used in a Lua script, Lua will pass the string parameter on its stack structure.

The Lua script could look something like this:
characterName = ‘Winnie the pooh’
winnieFighting = InCombat(characterName)

Its perfectly possible to mess up by calling the Lua function without any parameters or a parameter of a wrong type, there is no type checking, other than the defensive code you can and should implement in your .Net methods.

This concludes the post about registering and using c# methods from Lua.
Hope you found it usefull, please feel free to comment.

Thue Tuxen



Check out part III with source code for a simple lua script engine including a full managed wrapper and a sample program.

Embedding Lua in C# .Net – Part I

November 3, 2009

Recently I had to write a tool, which would be able to map one XML format to another.
I needed to be able to map a source XML and all its fields to a destination xml format with different kind of fields.

The list of requirements looked was looking something like this:
• Each field should be allowed a custom business rule to be applied when mapping to the destination, and these rules could be anything from doing some math, to look up a particular string depending on the nth element of any of the source XML arrays.
• It should also be possible to map a source array of elements of any type (custom included), to any destination array of any type.
• The mapping formats should be based on multiple fairly large XSD schemas
• The was no telling when business development department decided to change rules, mappings or the schemas themselves

This was looking to be a seriously pain in code modifications and recompilations of the tool, with endless support needed to maintain a valid tool.

… Or a seriously flexible and generic configuration engine that could manage every XSD schema, every mapping and every rule, so that all would be reconfigurable and the need for recompilations would be eliminated.

Thus any change in the schemas, mappings or business rules would just be configured by a user in the graphical UI of the tool itself, instantly changing the behaviour of the tool, without waiting for a new release of the tool, which would implement the new changes.

lua

Choosing the components of the tool
I really like .Net, especially because of the many build in stuff, the memory management and the easy way a useful GUI can be implemented rather quickly.
Also I’ve been using Lua when coding some small mods for World of Warcraft, and I thought the whole WoW extension experience with Lua scripting engine was some of the most amazing I had seen in flexibility ever.

I wanted to combine the two, and get this sort of flexibility into my tool, as I didn’t quite see how I was able to fulfil my requirements without some sort of dynamic scripting engine.
Lua has very good integration with C/C++ but not so straightforward with .Net.

Making .Net and Lua talk
Go to http://www.lua.org/ and download the latest source of this great great great engine.
Lua is free software distributed in source code. It can be used for any purpose, including commercial purposes, at absolutely no cost.

The calling convention problem
Unfortunately using a standard Lua dll directly from .Net will quickly crash your program.
This is due to different calling conventions in C/Lua vs. .Net.

Calling conventions is all about how functions go about calling other functions.
In particular how function parameters should be passed and who should remove them when the function returns.
In C/C++ the __cdecl (caller cleans) calling convention is the default, and in .Net the __stdcall (callee cleans) calling convention is the default.

If you don’t know anything about calling conventions, and don’t care, then please just skip the explanation stuff and go straight to the guide helping you build a Lua dll for use with .Net
.Net implements platform invoke calls as __stdcalls per default and you cannot change this behaviour, except modifying and reassembling .Net IL code.
At the return of the call from a .Net function to a Lua C function the program will crash because the functions can’t agree about who’s responsible for cleaning up the stack, and this will corrupt the stack.

Some examination
__cdecl marked functions:
The caller is responsible for cleaning any parameters sent on the stack to the callee (the called function).

Typically it will look like this, when calling a function named C with 1 parameter:
C(5);

It will look similar to this in assembly code
004017EB  push       5                         — prepare an integer argument on the stack
004017ED  call        C (4017D0h)  — push return address 004017F2 on the stack and change instruction pointer to  4017D0h

Callee processes something and finally issues a RET instruction which pops the return address into the IP instruction pointer register and proceeds execution at:

004017F2  add         esp,4               — the caller now cleans up the stack, freeing the 4 bytes containing the 32 bit integer with the value  5.

__stdcall marked functions:
The callee is responsible for cleaning any parameters sent to it on the stack.

Calling C(5);

004017EB  push       5                         — again preparing an integer argument on the stack
004017ED  call        C (4017D0h)  — again issuing a call instruction and push return address

In function C do stuff

004017D4  ret         4
As the function C returns it now calls RET with an argument 4, again freeing 4 bytes of stack space, cleaning the 32 bit argument passed to it.

Lua with .Net integration solutions
Based on the knowledge above, there are basically two paths you can take to integrate Lua with .Net.

A.
Configure a visual studio solution to correctly build the Lua source code so that the Lua dll will be directly accessible from .Net.
This is simply achieved by compiling Lua as a dynamic dll with the calling convention of the project explicitly set to __stdcall as default instead.

The drawback
Choosing this method disables the use of some functions with variable arguments.
Some features of the Lua API can no longer be called with variable number of arguments, the caller must match the exact signature of the function.
This is for most types of applications and usages not a major drawback, but in some cases it’s a really cool feature which would greatly ease some tasks.
Im not sure precisely where this is an issue, so I would appreciate any comments about it, if somebody else can make a precise statement!

B.
Write a bridging dll between Lua and .Net in C++/CLI.

C++/CLI (Common Language Infrastructure) is Microsoft’s language specification intended to supersede Managed Extensions for C++.
With this option you can create all the bridging to Lua in C++/CLI with support for both the c++ runtime and the .net common language runtime
The produced integration assembly can then be used by regular .Net solutions, just by adding a reference to it and working on it like any other .Net assembly.

Example of a project of a Lua bridging dll written in C++/CLI is LuaInterface which can be found here

The plusses of this method are that it enables the compilation of the functions communicating directly with Lua, to be declared with the __cdecl calling convention.
Any other method that will be called from extern .Net assemblies can be declared with the __stdcall calling convention.

This enabled the use of variable argument functions
(which will just discard arguments that does not fit its signature).
This is due to the fact that the __cdecl calling convention specifies that ‘Caller cleans the stack’.
The callee does not need to know how many arguments were passed to it, and the callee is not responsible for cleaning out the arguments, from the stack upon returning from the function.

Get to the point already!
I’ll be focusing on method A, as I found it the easiest to get up and running quickly, and I did not need the bit of functionality the method prohibited.

Building the Lua Dll with __stdcall
Create a new c++ dll project.

VS_project_Properties_Calling_Convention

Select DLL as the project type
select project type

After project creation, delete all the default files created in the project.
Add all the Lua source files, except ‘lua.c’ and ‘luac.c’, downloaded from lua.org to the projects header files folder and source files folder, lua.c and luac.c are standalone consoles that don’t belong in the core Lua dll.
 
Right click the project and choose properties.
In the configuration properties locate the calling convention setting like so.
VS_project_Properties_Calling_Convention

Set it to __stdcall.
OK your way out.

As per default Lua is setup to be build as a library .lib, and therefore no functions are exported when building as a dll.
This can be changed in luaconf.h, by setting the corresponding pre-processor directives, but the result is not exactly what I want in regards to .Net.
I’ll show it anyway, but you can skip the addition of adding the directives.
preprocessor defintiions

Add the LUA_BUILD_AS_DLL define
Add the LUA_CORE define

Note that this method results in the dll containing decorated names, which is OK for any other C/C++ program that can use the .lib that goes with the DLL but not for a .Net assembly if you want to use the original functions names in your imports.
Using decorated names
Build the solution, your now almost have the final Lua core dll that you can use from .Net.

Actually I ended up with using a module definition file (.def) instead for my exports from Lua.
This ensures that the dll exposes the exported function names without decoration.

I have uploaded a word doc with the contents of a complete example .def file for the dll if you prefer using the same method as me, just paste the contents into a text file and give it the .def extension and add to dll project.
Lua dll module definition file

Change the configuration properties of the dll project to use the .def file:
Associate module definition file

Using this method, you should just skip the other exporting method, i.e. changing of pre-processor directives etc.

MS documentation on dll export using a .def file here:
http://msdn.microsoft.com/en-us/library/d91k01sh(VS.80).aspx

Handling the issues with the C runtime manifest
OK, so far so good all we need now is too handle the dependence of the C runtime, and embed a manifest in our dll that tells which C runtime too use.

From http://lua-users.org:
The distributions for Lua 5.1.3 have moved (and probably sensibly) to assuming MSVCR80.DLL is present, and provide the required manifest resource to properly handle side by side versioning of the runtime

Were going to solve this using the Microsoft manifest tool.
Place the manifest and your Lua dll in the same folder and fire up a Visual Studio command line, and execute the following:
mt.exe /manifest Microsoft.VC80.CRT.manifest /outputresource:lua514.dll;2
(1 for an EXE, 2 for a DLL.)

The documentation for mt.exe describes using [-] as command prefix, but somehow my console translates that to [!!], so I used [/] and that worked…

DLL Done
We are now ready to use the Lua dll from .Net.
Anytime you use it, just plant it in your bin folder along with the C runtime ‘msvcr80.dll’.
I don’t know why but even though the manifest lies embedded into the Lua dll, the manifest file must also still be present as standalone in the bin directory, this kind of annoys me as I’m probably doing something wrong 🙂

Viewing the exported function names of your Lua dll
Open a Visual Studio cmd.exe and cd to the directory of the dll.
Use the Dumpbin tool like this: Dumpbin /EXPORTS <name of dll>

Using Lua from a C# .Net project
Create a new .Net console application
In the example I use a console app, because Lua will then be able to output to the stdout of the console window.

I suggest you make a static class to wrap the Lua dll.
The class will contain definitions from lua.h, and the wrappers for the Lua API.

The Lua state object is the single most central part of the Lua engine, you will use this state in any call to a Lua API function from .Net.
Here’s a very small sample wrapper class that implements some basic Lua API functionality.
With this class you can open a valid Lua State, execute a Lua script held in a string, outputting some text to the console window, and finally close the Lua state.


public static class Lua
{
   //some Lua defines
   /* option for multiple returns in `lua_pcall' and `lua_call' */
   public const int LUA_MULTRET = (-1);
     
   //the first of any calls to Lua.
   //get a valid Lua state to operate on
   [DllImport("lua514.dll")]
   public static extern IntPtr luaL_newstate();
  
   //open all Lua libraries
   [DllImport("lua514.dll")]
   public static extern void luaL_openlibs(IntPtr lua_State);
  
   //close Lua
   [DllImport("lua514.dll")]
   public static extern void lua_close(IntPtr lua_State);
  
   //load a Lua script string into the Lua state
   [DllImport("lua5.1.dll")]
   public static extern int luaL_loadstring(IntPtr lua_State, string s);
  
   //call a lua function, a function can be a Lua script loaded into the Lua state
   [DllImport("lua5.1.dll")]
   public static extern int lua_pcall(IntPtr lua_State, int nargs, int nresults, int errfunc);
  
   //simplify the execution of a Lua script
   public static int luaL_dostring(IntPtr lua_State, string s)
   {
      if(luaL_loadstring(lua_State, s) != 0)
          return 1;
      return lua_pcall(lua_State, 0, LUA_MULTRET, 0);
   }
  
   /*
   public static void LogError()
   {
      //log error
      string errMsg = null;
      if (Lua.lua_isstring(m_lua_State, -1) &gt; 0)
          errMsg = Lua.lua_tostring(m_lua_State, -1);
 
      //clear the Lua stack
      Lua.lua_settop(m_lua_State, 0);
         
      //log or show the error somewhere in your program
   }
   */
}

With our class defined we can now call Lua to do a simple calculation, this is our HelloWorld.
Codesnippet:

IntPtr lua_State = Lua.luaL_newstate();
if (lua_State == IntPtr.Zero)
{//error}

//open the Lua libraries for table, string, math etc.
Lua.luaL_openlibs(lua_State);

string luaScriptString = "TwoPlusTwo = 2+2; print('Hello World'); print('TwoPlusTwo:', TwoPlusTwo)";
if (Lua.luaL_dostring(lua_State, luaScriptString) != 0)
{//error}

//clean up nicely
Lua.lua_close(lua_State);

You should see something similar to this, outputted to the console window:
console output

I leave it to you to add the DllImports to get the LogError method working.
Any other Lua API function can be added to the class, just remember to add lua.h definitions as you go.

This wraps up my post on integrating Lua with C#/.Net, hope you enjoyed it, and that it was useful to you.

There are lots of things I haven’t shown here, like registering C# methods to Lua and to be able to call them from Lua script.

I have added how to call from Lua into c# in another post, Embedding Lua in C# .Net – Part II
Full source code for a sample working program including a simple script engine, and a full managed wrapper can be found in part III in this post

Thue Tuxen

Magnus Carlsen climbs above the 2800 barrier

October 26, 2009

With his incredibly solid victory in the Pearl Spring Chess Tournament 2009, Magnus carlsens rating is going to exceed the 2800 barrier for the first time.

According to the unofficial live ratings: http://chess.liverating.org/

Im looking forward to see how he will be doing in the 4. quarter of 2009.

In November, he plays the Tal Memorial in Moscow, followed in December by the London Chess Classic, and in January Corus Wijk aan Zee.

P.S

If only Hikaru Nakamura could pull himself together and be a true professional, im sure the chess scene 3-4 years ahead would be even more exciting than it is at present time.