C# 俺 dll 呼び出しのサンプル

C# から、C++ で作った dll の呼び出しをよく使うのでサンプルを置いておこうっと。

wchar_t* pLog = NULL; //!< とりあえずのログを置く

__declspec(dllexport) wchar_t* myTest(wchar_t* mes)
{
  if( pLog != NULL ){ delete pLog; pLog = NULL; }
  int len = wcslen( mes );
  pLog = new wchar_t[ len + 32 ];
  swprintf( pLog, L"%s:%d", mes, len );
  return pLog;
}

dll のプロジェクトに def ファイルを追加して、エクスポートする関数名を書くのも忘れずに。

LIBRARY	"hoge" // dll 名
EXPORTS
	myTest // 関数名

続いて、C# 側は以下のように書く。C++ の char は 1バイトですが、C# の Char は Unicode 用で 2バイトなので注意。

class TestDll
{
  [DllImport("hoge", EntryPoint = "myTest", CharSet = CharSet.Unicode)]
  public static unsafe extern Char* myTest(Char* mes);
 public unsafe static Main()
  {
    String mes = "こんにちは";
    String res;
    fixed (Char* pMes = mes.ToCharArray()) //!< pMes をガベージコレクションの対象から外す
    {
      Char* pRes = myTest(pMes); //!< dll 内の myTest を呼び出し
      res = new String(pRes);
    }
    Console.WriteLine(res);
  }
}