본문 바로가기
C++/C++ DLL

C++ DLL 을 C# 에서 사용하기 (구조체)

by doublerabbits 2022. 8. 29.

1. 프로젝트 만들기 및 속성은 이전 글 확인

 

C++ DLL 을 C# 에서 사용하기

 

C++ DLL 을 C# 에서 사용하기

1. Visual Studio 에서 솔루션 구성을 위한 빈 솔루션 생성 기타 프로젝트 형식 - Visual Studio 솔루션 - 빈 솔루션 2. C++ DLL 프로젝트 생성 추가 - 새 프로젝트 Visual C++ - Windows 데스크톱 - DLL(동적 연..

doublerabbits.tistory.com

 

 

2. CppLib - dllmain.cpp

// dllmain.cpp : DLL 애플리케이션의 진입점을 정의합니다.
#include "pch.h"

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

struct Person
{
	int age;
	char name[100];
};

extern "C" __declspec(dllexport) void SetPerson(struct Person * p, int age, char * name)
{
	memset(p, 0, sizeof(Person));
	p->age = age;
	memcpy(p->name, name, sizeof(name));
}

 

 

 

3. CSApp - Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace CSApp
{
    class Program
    {
        public struct Person
        {
            public int age;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
            public string name;
        }

        [DllImport("CppLib.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void SetPerson(ref Person p, int age, string name);

        static void Main(string[] args)
        {
            Console.WriteLine($"CppLib CSApp : struct");

            Person p1 = new Person();
            SetPerson(ref p1, 10, "John");

            Person p2 = new Person();
            SetPerson(ref p2, 20, "Jane");

            Console.WriteLine($"{p1.name} : {p1.age}");
            Console.WriteLine($"{p2.name} : {p2.age}");

            Console.ReadKey();
        }
    }
}

 

'C++ > C++ DLL' 카테고리의 다른 글

C++ DLL 을 C# 에서 사용하기  (0) 2022.08.29