配列型

概要

配列型のデータのやりとり

配列型

配列の場合は、値渡ししたとしても結局は配列の先頭アドレスがC++側に渡ることになりますので、 事実上は、「参照渡し」に近いこととなります。即ち、
C++側で配列内の値を変更すると、そのままC#側の配列オブジェクトにも反映される形となります。

  • C++側のソース

    Dll1.dllとしてコンパイル
    #include <windows.h>
    #include <cstddef>
    #include <iostream>
    
    using namespace std;
    
    #define DLLEXPORT __declspec(dllexport) WINAPI
    
    // BYTE配列受け取りと値の代入
    extern "C" void DLLEXPORT dllByteArray(BYTE arr[], int32_t size) {
    	cout << "元の配列" << endl;
    	for (int i = 0; i < size; i++) {
    		cout << fixed << (int)arr[i] << endl;
    	}
    
    	// 配列の内容に1を加える
    	for (int i = 0; i < size; i++) {
    		arr[i]++;
    	}
    }
    
    // int32_t配列受け取りと値の代入
    extern "C" void DLLEXPORT dllInt32Array(int32_t arr[], int32_t size) {
    	cout << "元の配列" << endl;
    	for (int i = 0; i < size; i++) {
    		cout << fixed << arr[i] << endl;
    	}
    
    	// 配列の内容を2倍にする
    	for (int i = 0; i < size; i++) {
    		arr[i] *= 2;
    	}
    }
    
    // double配列受け取りと値の代入
    extern "C" void DLLEXPORT dllDoubleArray(double arr[], int32_t size) {
    	cout << "元の配列" << endl;
    	for (int i = 0; i < size; i++) {
    		cout << fixed << arr[i] << endl;
    	}
    
    	// 配列の内容を1.5倍にする
    	for (int i = 0; i < size; i++) {
    		arr[i] *= 1.5;
    	}
    }
    
  • C#側のソース

    test1.cs
    using System;
    using System.Runtime.InteropServices;
    
    namespace test1
    {
        internal class Program
        {
            [DllImport("Dll1.dll")]
            static extern void dllByteArray(byte[] arr, Int32 size);
    
            [DllImport("Dll1.dll")]
            static extern void dllInt32Array(Int32[] arr, Int32 size);
    
            [DllImport("Dll1.dll")]
            static extern void dllDoubleArray(double[] arr, Int32 size);
    
    
            static void Main(string[] args)
            {
                byte[] a = new byte[] { 1, 2, 3,10, 22 };
                dllByteArray(a, a.Length);
    
                Console.WriteLine("結果の配列");
                foreach(var e in a)
                {
                    Console.WriteLine(e);
                }
    
    
                Int32[] b = new int[] { 10, 20, 30, 40, 50 };
                dllInt32Array(b, b.Length);
    
                Console.WriteLine("結果の配列");
                foreach (var e in b)
                {
                    Console.WriteLine(e);
                }
    
    
                double[] c = new double[] { 10.5d, 20.5d, 30.5d, 40.5d, 50.5d };
                dllDoubleArray(c, c.Length);
    
                Console.WriteLine("結果の配列");
                foreach (var e in c)
                {
                    Console.WriteLine(e);
                }
    
    
                 Console.ReadKey();
            }
        }
    }