Cで書いたDLLをC#から使いたい

Cで書いたDLLをC#から使いたい!と思い使い方を調べた。

コンパイラは手元のUbuntu(VMWare上、バージョンは10.04)にインストールしたMinGW(4.4.2)を使った。(sudo apt-get install mingw32)
DLLのビルド

$ i586-mingw32msvc-gcc --shared -o hoge.dll hoge.c

C#側では、DLLImportAttributeを指定して、dllの名前等の情報を指定し、extern staticなメソッドを定義するだけ。
あとはC#で作成した実行ファイルが参照できる場所にDLLをおいて実行する。

// TODO:構造体などのユーザ定義型の受け渡し方法を調べる
// TODO:C++呼び出し
// 参考:http://msdn.microsoft.com/ja-jp/library/aa288468(VS.71).aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// DLLImportAttribute
using System.Runtime.InteropServices;

namespace DLLFunctionCalling
{
    class Program
    {
        static void Main(string[] args)
        {
            Int32 x = 10;
            Int32 y = -4;
            Int32 z = Program.AddTwoNumbers(x, y);
            System.Console.WriteLine("{0} + {1} = {2}", x, y, z);

            float a = 2.3F;
            float b = 4.5F;
            float c = Program.AddTwoFloatNumbers(a, b);
            System.Console.WriteLine("{0} + {1} = {2}", a, b, c);
        }
        // // add.c
        // #include<stdio.h>
        // __declspec(dllexport)
        // int AddTwoNmbers(int x, int y)
        // {
        //     return x + y;
        // }
        // $ mingw --shared -o add.dll add.c
        [DllImport("add.dll", CallingConvention = CallingConvention.Cdecl)] 
        private static extern Int32 AddTwoNumbers(Int32 x, Int32 y);
        // // cppadd.c
        // template<class typex>
        // typex AddTwoObjects(const typex& x, const typex& y)
        // {
        //     return x + y;
        // }
        // extern "C" {
        // __declspec(dllexport)
        // double AddTwoFloatNumbers(float x, float y)
        // {
        //     return AddTwoObjects<float>(x, y);
        // }
        // }
        // $ mingw-g++ --shared -o cppadd.dll cppadd.cpp
        [DllImport("cppadd.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern float AddTwoFloatNumbers(float x, float y);
    }
}