Alieniloquent


Exposing .NET code in a DLL via C++

December 31st, 2006

At my work, we do both Delphi for Win32 and .NET. Most of our .NET coding is in C#, though, so we can’t just cross-compile. We have a number of .NET components that would be nice to use on the Win32 side (such as zip libraries), and we know its supposed to be possible, but none of us have ever gotten into the nitty gritty of actually doing it. Now, programming for Windows isn’t my favorite thing in the world. But, I do love a good technical challenge. Especially one that requires me to dust off a language I haven’t used in a while. This will be the first of a few articles documenting the things I’m learning from doing this.

The strategy that I’ll be using is to write a DLL in C++ that will allow the Delphi code to call into the .NET code. Microsoft’s C++ allows you to mix unmanaged and managed code fairly easily, so it makes for a very good glue layer in situations like this.

So, to start off, let’s make the Visual Studio project for the DLL. I’m using Visual Studio 2005 for this, and I’ll use the C++ CLR template entitled “Class Library.” I’ll give it a name “Example” and hit go. This makes most of the files that you need. Delete the class that it creates (”Class1″) and make a new one like this:

// Example.h

#include <vcclr.h>

#pragma once

using namespace System;

namespace Example {
 public class Example1
 {
 public:
  Example1(const char * name)
  {
   _name = gcnew String(name);
  }
  ~Example1()
  {
  }

  void ShowName();
 private:
  gcroot<String ^> _name;
 };
}

A couple things to note about the above code. The Example1 class is an unmanaged class, but the _name field is a managed object. The gcroot class takes care of telling the garbage collector about the managed string object.

Next, we need to export some DLL functions so that we can call them from Delphi:

// Exports.h
#define DLLAPI extern “C” __declspec(dllexport)

DLLAPI void * Example1Create(const char * name);
DLLAPI void Example1Delete(void * example);
DLLAPI void Example1ShowName(void * example);

The important thing to notice here is the DLLAPI define. You need to put it before each function you want to export. We have to extern the functions as C-style functions so that their names don’t get mangled in the symbol table.

// Exports.cpp
#include “stdafx.h”
#include “Example.h”
#include “Exports.h”

using namespace Example;

#define E1(p) ((Example1 *) p)

DLLAPI void * Example1Create(const char * name)
{
 return new Example1(name);
}

DLLAPI void Example1Delete(void * example)
{
 delete example;
}

DLLAPI void Example1ShowName(void * example)
{
 E1(example)->ShowName();
}

Note the macro defined to do the cast. We only have to do the cast in one place right now, but as you expose more methods on the object, you’ll have to cast for every one. The macro makes it easier.

So to summarize what we have so far. In the DLL we have an unmanaged class which can access the managed classes in .NET. Then we expose functions which can create instances, destroy them, and call methods on them. These return pointers which the caller must manage. The pointers are passed into all of the functions which invoke methods, and those functions cast and then call.

In my next post I’ll show how to consume this DLL from Delphi.

Movie Reviews: All the King’s Men

September 21st, 2006

When I first saw the trailer for this movie, I didn’t think I’d ever see it. The story didn’t seem like the kind I tend to enjoy. But, when a friend of mine offered to give me some free tickets I figured it was worth seeing for free, and it’s a good thing I did. This way I can tell you about how terrible the movie is, and hopefully save you some cash.

The budget for the film was $55 million. A fairly small budget by Hollywood standards, but in the same range as the last three films I saw: The Covenant ($20 million), Snakes on a Plane ($36 million), World Trade Center ($65 million). I liked all of those films, but I didn’t like this one, and I think it really comes down to how the budget was spent.

Two places the producers clearly did not spend their budget was on cinematography or editing. In no fewer than four scenes I saw the head of a boom mic bouncing along the top of the screen, and in one scene I saw the mic and its boom in their entirety. This isn’t like a car in Lord of the Rings. This is just shoddy movie-making.

Another place they clearly did not spend their money was writing. I’m sure that the book this movie was based on was a fine novel. I know there was a real story about Huey Long, whom this story is loosely about. Somehow, though, the writers for this film failed to caputre any real plot. None. None at all.

I think where they spent almost all their money was on casting. The movie had an amazing cast: Sir Anthony Hopkins, Jude Law, Kate Blanchett, Mark Ruffalo, Sean Penn, and James Gandolfini. Those are some big names, and I’m sure they all had nice fat paychecks for their performances. The performances were even decent, although Penn summoned memories of Snatch with his thick, unintelligible accent.

So, if you want to play spot-the-mic, or want to see if you can find the plot, go see this movie. But, if you want to enjoy the two hours you’ll spend watching it, go do something else.

Drawing graphs and automata in LaTeX

September 21st, 2006

I am currently enrolled in a class entitled “Automata, Computability, and Formal Languages” at UNO. It’s a neat class. The professor requires us to submit our homework in both hard and soft copies. Naturally, he suggests we use LaTeX to typeset our homework.

Given that this is a class on automata, I end up drawing a lot of state diagrams to represent the machines I have to design for the problems. I wanted a nice way to draw these and put them in to my LaTeX document. The first thing I did was check to see if OmniGraffle exported to EPS, and it did. LaTeX can read EPS, so I was okay if I couldn’t find anything better.

With a solution in hand, I started to look and see if there was anything I could use to typeset these graphs right in the LaTeX source itself. Preferably something designed for drawing finite state-machines, even. What I found was GasTeX. It is a decently cool package.

The following source code from their samples page:

\begin{figure}[H]
  \begin{center}
    \unitlength=4pt
    \begin{picture}(15, 28)(0,-10)
      \gasset{Nw=5,Nh=5,Nmr=2.5,curvedepth=3}
      \thinlines
      \node(A0)(7.5,0){$0$}
      \node[Nmarks=i,iangle=90](A1)(0,13){$1$}
      \node[Nmarks=if,iangle=90,fangle=90](A2)(15,13){$2$}
      \drawloop[loopangle=180](A1){$a$}
      \drawloop[loopangle=0](A2){$b$}
      \drawedge(A1,A2){$a$}
      \drawedge(A2,A1){$b$}
      \drawedge(A2,A0){$a$}
      \gasset{curvedepth=-3}
      \drawedge[ELside=r](A1,A0){$b$}
      \drawloop[loopangle=270](A0){$a, b$}
    \end{picture}
  \end{center}
  \caption{La complétion de l’automate.}
\end{figure}

Generates this graph (which I have scaled down):

Example of GasTeX output

One note about this snippet, though, is that I did not have to use the center environment to center the figures. Instead I used the \centering directive inside my figure environment, and that worked nicely.

It’s nice to use and it makes pretty graphs. I’ll be using it for the rest of the semester, that’s for sure!

Making Active Directory liveable for Linux

September 14th, 2006

So my employer’s network is a Windows network. This isn’t terribly unusual. Our department’s version control server, however, is a Linux box. We didn’t want to have to have more than one password, so back when I set it up, I took the time to figure out how to get it to authenticate to Active Directory for us. It’s really cool, actually. Samba is really awesome.

However, we have had a few problems. The thing is that every so often, our Linux server was being removed from the Windows domain. So then we couldn’t authenticate users, and so we couldn’t check out our source code. Obviously, that causes problems.

It turns out that adding one line to the [global] section of my smb.conf file is what is needed to solve the problem. See, the Windows boxes check in with the Active Directory controller once a day to update their machine ID. My server was not doing this. I’ve found, over time, that there are a lot of options for making Samba play well in a Windows network that aren’t really defaulted like they should be. Below is what I added to make it update like the others.

machine password timeout = 86400 # one day

Another interesting thing, was that despite my not telling it to, Samba was advertising the machine as a domain controller. So I had to add the line below to disable that (despite the docs saying I shouldn’t have to).

domain master = no

In addition to the rest of the configuration for Samba to work with Active Directory, and I think we may finally have it working all the way.

Podcast

September 4th, 2006

So I decided to start a pod cast. Check it out: The Agile Mac.

J3Testing 1.0

September 1st, 2006

I decided to make my J3TestCase code into an actual framework. This way I don’t have to copy the files each time I want to use the class.

I’ve put up a disk image with binaries and one with source.
The source is worth looking at, especially to see how I made targets to automatically build those disk images.

These replace the old J3TestCase code I had posted, and I’ve removed that tarball. So, sorry if I broke that link. This is a much better way to deploy anyway.

Quirky Behavior in String#gsub

August 31st, 2006

At my office I develop in Delphi. We use Delphi 2006. As far as IDEs go, it’s not that great. For example, when you tell the Delphi 2006 IDE to do a build all (something you’d think developers do quite frequently), it has a very annoying behavior: it eats up scads of memory. In fact when the build all operation completes on our project group, Delphi has laid claim to over 1GB of memory, and it won’t let it go until you quit the application. But, this post isn’t about Delphi or its buggy IDE. It’s about ruby. More specifically, it’s about a quirk (read: bug) in ruby.

The String class in ruby has a method called gsub. This method takes two parameters and each can take two types of object. The first parameter can either be a Regexp or a String, and it represents what is to be replaced. The second can either be a String or a block, and supplies the value with which to replace it. This seems perfectly natural.

Now, if you’ve ever used regular expressions, you probably know about back-references. When you use the grouping operator in a regular expression (e.g. ^a(ab)b$) it stores a numbered back-reference to the matched value of each group. In ruby you can reference these with the special variables $1, $2, and so on. But, if you are passing a string as the replacement, it will only be interpolated once and those back-references won’t be correct. So, what gsub does is let you put in \1 and \2 instead.

That behavior is awesome, and exactly what you want, if you’re matching a regular expression. But if you’re just matching a string literal, there is absolutely no reason to do it. In fact, if all you’re doing is matching a string literal those back-references will all be the empty string.

So, how do I know all this? Well, because Delphi 2006’s build all operation bites, we wrote a ruby script to replace it. This script has to do file-name manipulation and all sorts of other string manipulation in order to get all of the correct compiler options. One of the things it does is replace strings like $(CodeBase) with a path such as c:\svn\trunk. Well, we have separate code bases for our branches, and they have names like c:\svn\2006. You see that \2 there? Yeah, that one, right in the middle of the path. Even though the script was matching a string literal, gsub was replacing back-references. Since the path happened to have a \2 in it, it would end up coming out of gsub as c:\svn006, and that certainly wasn’t right.

Thankfully, there is a simple work around. Instead of providing a string for the replacement, we can provide a block. That block gets called every time and the value that it returns is exactly what gets used as the replacement.

Regular Periodical Content

August 30th, 2006

So I’ve been thinking about starting some sort of periodic content: perhaps a regular themed article here or a podcast. I would like to take advantage of what readers I do have to see what people would like to hear me talk about.

Here are some topics that I’ve thought about doing:

  • Things about programming they don’t teach you in college
  • Agile methods
  • Test-first design
  • Refactoring
  • Cocoa programming
  • Ruby programming
  • Lisp programming

There’s no particular order to those, as I find them all very interesting. It’s possible that I could end up doing a mishmash of all of them.

Please leave a comment with a topic you’d like to hear me talk about!

YAGNI: byte-order conversion explained

August 30th, 2006

In my previous post I talked about this problem I ran into with byte-ordering and tests failing. Brian and Joe both felt that I left them hanging by going into all the technical details of what my problem was and not going into the technical details of why I shouldn’t have used htons to start with. Rather than editing the other post, here’s a new one.

The code that I was using htons in was my SOCKS5 implementation. For those who aren’t familiar with SOCKS5, it is a proxying protocol. The computer connects to the proxy and sends it a hostname and port for the actual connection. The proxy then makes the connection and relays packets for the remainder of the session.

Some of you may be guessing what I was calling htons on already: the port to be serialized. Here are the two offending lines of code:

[buffer append:(0xFF00 & htons(port)) >> 8];
[buffer append:(0x00FF & htons(port))];

That buffer was then, in turn, written out across the socket to the server (or inspected by unit tests). But, since I was extracting each byte individually the byte-order didn’t matter since 0xFF00 will be in the same byte order as port every time.

I hope this explains things a little better.

The Grandiloquent Dictionary

August 29th, 2006

So I was looking up an actual dictionary definition of “alieniloquent” today. I had one at some time in the past, but it’s a hard word to find in dictionaries, and that’s why I picked it for my domain. I finally found this website, the Grandiloquent Dictionary, and it has my word in it.

alieniloquent
Speaking discursively or straying from one’s point.

So for those of you who were wondering, there you go.

Layout, design, graphics, photography and text all © 2005-2007 Samuel Tesla unless otherwise noted.

Portions of the site layout use Yahoo! YUI Reset, Fonts & Grids.