整数型

概要

整数型のデータのやりとり

整数型

intやshortやlongといった一体何ビットになるのかOS違いなどであやふやになる型を利用するのはやめましょう。
はっきりと、「int32_t」「int16_t」「uint32_t」など「何ビット」か明示し、C#側もそれと一致させることで
x86とx64どちらに切り替わったとしてもビット数が変化してしまうことを事前に防止できます。
ただし、Windows/VC++で考えれば、
C++側は:short=int16_tint=long=int32_tlong long=int64_tと考えて良いでしょう。
C#側は:short=Int16int=Int32long=Int64なのでlongまわりを勘違いしないよう気をつけましょう。

  • C++側のソース

    Dll1.dllとしてコンパイル
    #include <windows.h>
    #include <cstddef>
    #include <iostream>
    
    using namespace std;
    
    #define DLLEXPORT __declspec(dllexport) WINAPI
    
    // ただの int といった型を使うと、x86とx64でビット数が安定しなくなる
    // 明示的に、int32_t、int64_t といった形でビット数を決め打ちすることで
    // x86でもx64でも同じビット数になり安定する。
    
    // int32受け取り
    extern "C" void DLLEXPORT dllint32(const int32_t a) {
    	cout << a << endl;
    }
    
    // uint32受け取り
    extern "C" void DLLEXPORT dlluint32(const uint32_t b) {
    	cout << b << endl;
    }
    
    // int16受け取り
    extern "C" void DLLEXPORT dllint16(const int16_t c) {
    	cout << c << endl;
    }
    
    // int64受け取り
    extern "C" void DLLEXPORT dllint64(const int64_t d) {
    	cout << d << endl;
    }
    
  • C#側のソース

    test1.cs
    using System;
    using System.Runtime.InteropServices;
    
    namespace test1
    {
        internal class Program
        {
            [DllImport("Dll1.dll")]
            static extern void dllint32(Int32 a);
    
            [DllImport("Dll1.dll")]
            static extern void dlluint32(UInt32 b);
    
            [DllImport("Dll1.dll")]
            static extern void dllint16(Int16 b);
    
            [DllImport("Dll1.dll")]
            static extern void dllint64(Int64 b);
    
    
            static void Main(string[] args)
            {
                int a = 100;
                dllint32(a);
    
                uint b = 200;
                dlluint32(b);
    
                short c = short.MaxValue;
                dllint16(c);
    
                long d = 11111111000000;
                dllint64(d);
    
                Console.ReadKey();
            }
        }
    }