LoginSignup
2
2

More than 3 years have passed since last update.

UnityでC++Puligin(Mac)

Last updated at Posted at 2020-11-13

UnityでC++を使いたい

UnityでC++のコードを使いたいけどいまいちよく分からない
Windowsでの記事はたくさんあるがMacの記事は少ない
X Codeをインストールすればいいらしいけど、そんな機能の割に容量の喰うアプリを入れたくないと言うことでUnityとC++の開発環境(g++/clang++)があればできる方法を伝えます。
ターミナルでg++は使える前提で話をします。

C++ファイルの作成

lib.h
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

extern "C"
{
    int sum(int a, int b); // a+bを求める関数
    int listsum(int* array, int size); // 配列の総和を求める関数
};

lib.cpp
#include "lib.h"

int sum(int a, int b)
{
    return a + b;
}

int listsum(int* array, int size)
{
    int r = 0;
    for (int i=0;i<size;i++)
    {
        r += array[i];
    }
    return r;
}

ビルドしてUnityで使う

Apple clangを使ってビルドします
Apple clangの導入方法はターミナルで clang または gccと打つだけ
あとは指示に従だけ......

clang++ --version または g++ --version と打ってみて何も異常がなければ大丈夫です
多分、clangと一緒にclang++もインストールされると思う

実は、Macのg++コマンドというのは、clang++コマンドのリンクが貼ってあるだけ
本当のg++の使い方はまた今度......

$ clang++ -dynamiclib -o lib.bundle lib.cpp

UnityでC#と連携

MainScript.cs
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;


static class DLL
{
    [DllImport("lib")]
    public static extern int sum(int a, int b);
    [DllImport("lib")]
    public static extern int listsum(System.IntPtr array, int size);
}
public class MainScript : MonoBehaviour
{
    public int[] Array;
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log(DLL.sum(1, 2));
        System.IntPtr ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(int)) * Array.Length);
        Marshal.Copy(Array, 0, ptr, Array.Length);
        Debug.Log(DLL.listsum(ptr, Array.Length));
        Marshal.FreeCoTaskMem(ptr);
    }

    // Update is called once per frame
    void Update()
    {

    }
}

Asset内の適当なフォルダにlib.bundleを置いてUnityEditor上から配列の中身を適当に設定して実行する。

ちゃんとConsoleに出力されれば成功!!!

参考サイト

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2