かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

UnityからCの関数を呼ぶ(プラグインの作り方)

苦痛。

Win32プロジェクトを作る。64bit環境なら64bitでdllを作るようにすること。

// Header.h
extern "C"
{
    __declspec (dllexport) int Add(int x, int y);
}
// Win32Project1.cpp : DLL アプリケーション用にエクスポートされる関数を定義します。
//

#include "stdafx.h"

__declspec (dllexport) int Add(int x, int y)
{
    return x + y;
}

ヘッダーは適当なところでincludeしておくといい。

DLLのコピー

UnityのAssets/PluginsにDLLをコピーする。

相互運用のコードを書く

適当なBehaviourあたりに以下のコードを書いたら動いた。

 [DllImport("Win32Project1")]
 private static extern int Add(int x, int y);

 // Use this for initialization
 void Start()
 {
     Debug.Log(Add(10, 20));
 }