コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】C++ から配列を受け取るサンプル

概要

f:id:baba_s:20211212203826p:plain

Visual Studio の「ファイル > 新規作成 > プロジェクト」を押して

f:id:baba_s:20211212203828p:plain

C++ の「ダイナミック リンク ライブラリ (DLL)」を選択して「次へ」を押して

f:id:baba_s:20211212203837p:plain

適当にプロジェクト名を設定して「作成」を押して

#include "pch.h"

#define DLLEXPORT extern "C" __declspec(dllexport)

static int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

DLLEXPORT void __stdcall get_array(int** result, int* count)
{
    *result = array;
    *count = 10;
}

「dillmain.cpp」に上記のコードを貼り付けて

f:id:baba_s:20211212203839p:plain

ソリューションプラットフォームのプルダウンメニューで「x64」を選択して

f:id:baba_s:20211212203841p:plain

「ビルド > ソリューションのビルド」を押して
.sln が存在するフォルダに作成された「x64/Debug」フォルダ内の .dll を

f:id:baba_s:20211212203844p:plain

Unity の Plugins フォルダに格納します

using System;
using System.Runtime.InteropServices;
using UnityEngine;

public class Example : MonoBehaviour
{
    [DllImport( "Dll1" )]
    private static extern void get_array( ref IntPtr array, ref int count );

    private void Awake()
    {
        var array = IntPtr.Zero;
        var count = 0;

        get_array( ref array, ref count );
        var result = new int[count];
        Marshal.Copy( array, result, 0, count );

        Debug.Log( $"count: {count}" );

        for ( var i = 0; i < result.Length; i++ )
        {
            var value = result[ i ];
            Debug.Log( $"index {i}: {value}" );
        }
    }
}

後は C# で上記のようなコードを作成して実行すると
C++ から配列を受け取れることが確認できます