개발/C++

3. c# string을 c++ DLL로 전달하는 방법

njsung 2023. 2. 1. 18:39
반응형

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

2023.01.31 - [개발/C++] - 2. C++ DLL을 C#에서 이용하기

방법1. std::wstring 사용

C++ DLL 코드

#include <string>

extern "C" __declspec(dllexport) void FunctionName(const std::wstring& inputString)
{
	std::wcout << inputString << std::endl;
}

C# 코드

using System;
using System.Runtime.InteropServices;

class Program
{
    [DllImport("MyCppDll.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
    public static extern void FunctionName(string inputString);

    static void Main(string[] args)
    {
        string inputString = "Hello, C++ DLL!";
        FunctionName(inputString);
    }
}

 

728x90

방법2. char* 사용

C++ DLL 코드

#include <string>

extern "C" __declspec(dllexport) void FunctionName(const char* inputString)
{
	std::cout << inputString << std::endl;
}

C# 코드

using System;
using System.Runtime.InteropServices;

class Program
{
    [DllImport("MyCppDll.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
    public static extern void FunctionName(string inputString);

    static void Main(string[] args)
    {
        string inputString = "Hello, C++ DLL!";
        FunctionName(inputString);
    }
}
반응형