C++のdllをC#で呼び出す

アフィリエイト広告を利用しています

C++のダイナミックライブラリ(.dll)を選択する

C++のソースコード

// C++コード (dllmain.cpp)
#include "pch.h"
#include <iostream>
#include <cstring>

extern "C" {
    __declspec(dllexport) int Multiply(int a, int b) {
        return a * b;
    }
}

DLLが64ビットでコンパイルする。環境にあわせてコンパイルする。

C#のコード

// C# コード
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace DemoApp
{
    class NativeMethods
    {
        [DllImport("C:\\C_DEV\\ConsoleApp1\\ConsoleApp1\\bin\\Debug\\Dll1.dll", EntryPoint = "Multiply", CallingConvention = CallingConvention.Cdecl)]
        public static extern int Multiply(int a, int b);
    }

    class Program
    {
        static void Main(string[] args)
        {
            int result = NativeMethods.Multiply(5, 9);
            Console.WriteLine("5 multiplied by 9 is " + result);
            Console.WriteLine("終了するには何かキーを押してください。");
            Console.ReadKey();

        }
    }
}

デバッグ

「開始」をクリックしてデバッグを行います。

コメント

Loan Calculator

ローン計算

万円
%
ヶ月

タイトルとURLをコピーしました