.NET の不思議

C# for the Dummy の真似をしてやってみた。

% gcc --version
powerpc-apple-darwin8-gcc-4.0.0 (GCC) 4.0.0 20041026 (Apple Computer, Inc. build 4061)
Copyright (C) 2004 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


% mono --version
Mono JIT compiler version 1.1.9, (C) 2002-2005 Novell, Inc and Contributors. www.mono-project.com
        TLS:           normal
        GC:            Included Boehm (with typed GC)
        SIGSEGV      : normal
        Globalization: normal


% cat mac.c
/**
 * mac.c native C
 */
#include <stdio.h>

//say
void say( const char* s )
{
        printf( "%s?n",s );
}


% cat echomac.cs
/**
 * echomac.cs Wrapper for mac.c
 */
using System;
using System.Runtime.InteropServices;
    
namespace Mac
{
        public class EchoMac
        {
                [DllImport("mac.dylib", CallingConvention=CallingConvention.Cdecl)]
                static extern void say( string s );

                string myString;

                public EchoMac( string s )
                {
                        myString = s;
                }
            
                public void Say()
                {
                        say( myString );
                }
        }
}


% cat hello.cs 
/**
 * hello.cs Main
 */
using System;
using Mac;

public class Hello
{
        public static void Main()
        {
                EchoMac t = new EchoMac( "Hello Mono World" );
                t.Say();
        }
}


% gcc -dynamiclib mac.c -o mac.dylib
% mcs /t:library /out:echomac.dll echomac.cs
% mcs /out:hello.exe /r:echomac.dll hello.cs
% mono hello.exe
Hello Mono World

 
% ls -l
total 88
-rw-r--r--   1 hiro  hiro   391 Sep 19 13:27 echomac.cs
-rwxr-xr-x   1 hiro  hiro  3072 Sep 19 13:37 echomac.dll*
-rw-r--r--   1 hiro  hiro   168 Sep 19 13:27 hello.cs
-rwxr-xr-x   1 hiro  hiro  3072 Sep 19 13:38 hello.exe*
-rw-r--r--   1 hiro  hiro   113 Sep 19 13:31 mac.c
-rwxr-xr-x   1 hiro  hiro  9644 Sep 19 13:37 mac.dylib*% 
% 

C++ の関数を使うのはしんどそうだが、C の関数ならいけそうだ。
OpenGL のラッパーもこうやって作られているのだろうか。