개발/C++

2. C++ DLL을 C#에서 이용하기

njsung 2023. 1. 31. 13:26
반응형

2023.01.31 - [개발/C++] - 1. VS 2019에서 C++ 프로젝트를 DLL로 빌드하기

 

1. C++ DLL을 C#에서 사용하는 간단한 예제

 

C++ DLL(CPP.dll)

#include <Windows.h>

extern "C" __declspec(dllexport) int AddNumbers(int a, int b) {
  return a + b;
}

C#

using System;
using System.Runtime.InteropServices;	//import하지 않으면 DLLImport 사용 불가!

namespace CSharpApp {
  class Program {
    [DllImport("CPP.dll")]
    public static extern int AddNumbers(int a, int b);

    static void Main(string[] args) {
      Console.WriteLine("Result: " + AddNumbers(3, 5));
      Console.ReadKey();
    }
  }
}
728x90

2. C++ Class DLL을 C#에서 사용하는 간단한 예제

 

C++ DLL(CPP.dll)

#include <Windows.h>

class MathClass {
public:
  int AddNumbers(int a, int b) {
    return a + b;
  }
};

extern "C" __declspec(dllexport) MathClass* CreateInstance() {
  return new MathClass();
}

extern "C" __declspec(dllexport) int AddNumbers(MathClass* instance, int a, int b) {
  return instance->AddNumbers(a,b);
}

C#

using System;
using System.Runtime.InteropServices;

namespace CSharpApp {
  class Program {
    [DllImport("CPP.dll")]
    public static extern IntPtr CreateInstance();

    [DllImport("CPP.dll")]
    public static extern int AddNumbers(IntPtr instance, int a, int b);

    static void Main(string[] args) {
      IntPtr instance = CreateInstance();
      Console.WriteLine("Result: " + AddNumbers(instance, 3, 5));
      Console.ReadKey();
    }
  }
}

 

결론

C++ DLL을 Import한 뒤 클래스를 이용하기 위해서는 일종의 wrapper를 생성해줘야함. Instance를 전달하며 내부 함수를 wrapping한 함수를 호출하면 사용이 가능함.

SMALL

 

반응형