유니티(5), 개인/무료 및 전문가 사이에는 엔진 기능면에서 차이가 없다. 이는 이것을 의미한다. "Native Code Plugin Support"(네이티브 코드 플러그인 지원이) 더 이상 문제가 되지 않습니다. DLL 및 C++(unmanaged) 코드 제한이 없습니다.


이 가이드는 정말 만 유니티 5 (유니티4) 에 적용.


비 관리 및 관리 코드를 취급하는 경우 P/Invoke, marshaling, interoperability 등과 같은 표현은 주위 발생되었습니다. 모든 문제는 조금 어려울 수 있습니다.


이 가이드에서는 유니티 무료/Standard 와 유니티Pro 중 DLL을 취급 합니다. 하지만 유니티 무료로 네이티브(비 관리) 코드 장벽은 관리되지 않는 코드를 사용할 수 있습니다.


개요

구체적으로는 C# 참조 /에 C를 의존하는 DLL + 관리되지 않는 DLL을 관리 한 다음 Unity에서 이러한 기능을 사용 만들게 됩니다.


TLDR; For Unity 4 Pro and Unity 5 :

  • 플러그인 폴더에 모든 코드 / DLL 을 추가: UnityProject->Plugins

TLDR; For Unity Free : 

  • 유니티 프로젝트 루트에 관리되지 않는 코드를 추가 : UnityProject
  • 플러그인 폴더로 관리 코드를 추가 : UnityProject->Plugins
  • 프로젝트를 빌드 할 때, 관리되지 않는 코드를 복사 BuildRoot->Data->Plugins

Create a C++ DLL (Unmanaged)

To Start, 다른 조각에 의존하는 관리되지 않는 DLL을 만들 수 있습니다.

  • In Visual Studio, Create a New Project: Visual C++->Win32->Win32 Console Application
  • Name it TestCPPLibrary
  • [OK] 를 누른 후 팝업 응용 프로그램 설정 마법사의 경우 : 변경 Application Type to DLL
  • 같은 페이지에 빈 프로젝트 확인란을 선택합니다.

  • 다음 두 개의 파일을 만들고 내용을 붙여 넣기

TestCPPLibrary.h

1
2
3
4
5
6
7
8
9
10
11
12
// TestCPPLibrary.h
 
#ifdef TESTFUNCDLL_EXPORT
#define TESTFUNCDLL_API __declspec(dllexport) 
#else
#define TESTFUNCDLL_API __declspec(dllimport) 
#endif
 
extern "C" {
    TESTFUNCDLL_API float TestMultiply(float a, float b);
    TESTFUNCDLL_API float TestDivide(float a, float b);
}
cs


TestCPPLibrary.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// TestCPPLibrary.cpp : Defines the exported functions for the DLL application.
//
 
#include "TestCPPLibrary.h"
 
extern "C" {
    float TestMultiply(float a, float b)
    {
        return a * b;
    }
 
    float TestDivide(float a, float b)
    {
        if (b == 0) {
            return 0;
            //throw invalid_argument("b cannot be zero!");
        }
 
        return a / b;
    }
}
cs


Create a C# DLL (Managed)

  • In Visual Studio, Create a New Project : Visual C#->Windows->Class Library
  • Name it TestCSharpLibrary
  • 당신의 C# 을 솔루션에 C++DLL 을 추가
    • 당신의 C# 프로젝트 솔루션을 오른쪽 클릭 한 후 Add->Existring Item

    • Browse and choose your TestCPPLibrary project.
  • 바로 당신의 C# 프로젝트를 클릭하고 갑니다. Properties
  • In the Application tab, change the Target Framework to T.Net Framework 3.5

  • 다음 파일을 만들고 내용을 붙여 넣기

TestCSharpLibrary.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System;
using System.Runtime.InteropServices;
 
namespace TestCSharpLibrary
{
    public class TestCSharpLibrary
    {
        // From c++ Dll (unmanaged)
        [DllImport("TestCPPLibrary")]
        public static extern float TestMultiply(float a, float b);
 
        // From c++ Dll (unmanaged)
        [DllImport("TestCPPLibrary")]
        public static extern float TestDivide(float a, float b);
 
 
        public static float SharpMultiply(float a, float b) {
            return (a * b);
        }
 
        public static float SharpDivide(float a, float b) {
            if (b == 0)
            {
                return 0;
            }
 
            return (a / b);
        }
    }
}
cs


Build (Make the DLLs)

적절한 솔루션을 눌러 Build (F7) 을 클릭합니다. 당신이 나타날 때까지 그것을 실행합니다.

 ========== Build : 2 succeeded, 0 failed, 0 up - to - date, 0 skipped ========== 


당신은 C# 프로젝트 폴더 모두 DLL 을 찾을 수 있을 것입니다 : 

  • TestCSharpDll\TestCSharpLibrary\Debug\TestCPPLibrary.dll
  • TestCSharpDll\TestCSharpLibrary\TestCSharpLibrary\bin\Debug\TestCSharpLibrary.dll

Add the DLLs to your Unity Project

이후 native(unmanaged, the c++ DLL in our case) is a Pro/Mobile-only feature, it is quite easy to get this running in Uinty Pro, but Unity Free / Standard / Indie 는 복잡하고 귀찬타.


Unity Pro and any Unity 5


if you are using Unity Pro,

  • Copy both DLLs(TestCSharpLibrary.dllTestCPPLibrary.dll) into UnityProject->Plugins

당신은 빌드하면 프로젝트는 Unity 편집기에서 작업합니다.


Uinty (Free/Standard/Indie)


if you are using the standard version of Unity : 

  • Copy TestCSharpLibrary.dll, the C# managed DLL, into UnityProject->Plugins
  • Copy TestCPPLibrary.dll, the C++ unmanaged DLL, into the UnityProject root.

이 프로젝트가 Unity 편집기에서 수행 할 수 있지만 빌드에서는 작동하지 않습니다.

빌드 작업 프로젝트를 얻으려면... 당신은 당신의 프로젝트를 빌드 한 후 : 

  • Copy TestCPPLibrary.dll, into your Build Root->Data->Plugins, alongside your other DLL

Using the DLL in Unity

여기에 DLL을 사용하는 간단한 스크립트 입니다 : 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System.IO;
 
public class UseDll : MonoBehaviour {
 
    // Straight From the c++ Dll (unmanaged)
    [DllImport("TestCPPLibrary", EntryPoint="TestDivide")]
    public static extern float StraightFromDllTestDivide(float a, float b);
 
    // Use this for initialization
    void Start () {
 
        /* */
        // Call the C# DLL SharpMultiply function
        float multiplyResult = TestCSharpLibrary.TestCSharpLibrary.SharpMultiply(35);
 
        // Call the C# DLL TestDivide function which relies on the C++ DLL for this functionality
        float divideResult = TestCSharpLibrary.TestCSharpLibrary.TestDivide(153);
 
        float straightFromDllDivideResult = StraightFromDllTestDivide(205);
 
        // Print it out to the console
        Debug.Log(multiplyResult);
        Debug.Log(divideResult);
        Debug.Log(straightFromDllDivideResult);
 
        // Write the result into a file, so we can even see it working in a build
        using(StreamWriter writer = new StreamWriter("debug.txt"true))
        {
            writer.WriteLine(multiplyResult);
            writer.WriteLine(divideResult);
            writer.WriteLine(straightFromDllDivideResult);
        }
        /* */
 
    }
 
    // Update is called once per frame
    void Update () {
 
    }
}
cs


콘솔에 출력 스크립트를 실행해야하고, debug.txt 에 쓰기 : 


Running into Issues?

Internal compiler error ...  System.Reflection.ReflectionTypeLoadException 

당신의 내부 컴파일러 오류와 같은 오류가 발생하는 경우. Unity 중 System.Reflection.ReflectionTypeLoadException 프로젝트를 빌드하려고하고 있습니다. 당신은 .NET3.5 같은 것을, 당신의 C# 파일의 대상이 되는 .NET 버전을 변경해야합니다.

  • Right click on your C# project and go to Properties
  • In the Application tab, change the Target Framework to T.Net Framework 3.5



Failed to load ... expected 64 bit architecture (IMAGE_FILE_MACHINE_AMD64), but was IMAGE_FILE_MACHINE_I386


당신의 오류가 발생하는 경우는 아마도 x64 플랫폼 (64비트)를 위해 당신의 라이브러리를 재 컴파일 해야합니다.

Visual Studio에서 클릭하여 맨 위에 다음 당신의 프로젝트 속성으로 이동하여 "Configuration Manager의 ..."버튼을 클릭합니다. 표는 플랫폼의 열 아래에 "x64의"그런 다음 프로젝트를 다시 컴파일하도록 변경.


(블로그 주인) 비주얼 스튜디오 2012 버전 이후부터 32 bit, 64 bit 를 설정할 수 없다. 유니티의 버전을 32bit 로 다운 받아서 실행 해보자.





원본 링크 : http://ericeastwood.com/blog/17/unity-and-dlls-c-managed-and-c-unmanaged


  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기