Unity3D调用外部DLL

时间:2015-03-25 14:46:30

标签: c# c++ dll visual-studio-2013 unity3d

我正在尝试为Unity3D Pro(5.0)构建一个原生插件。到目前为止,我已经在VS Express 2013 for Windows中构建了一个DLL文件,我已经为此创建了一个示例Unity项目并链接了库,但我仍然收到错误,我似乎无法移动。谷歌在这件事上并没有那么有用......

我正在尝试为Windows Store目标添加一个带有我自己的低级内容的DLL。

我尝试以这种方式访问​​的内容并不重要,我被卡在hello world示例应用中。

Visual Studio项目

Dll3.cpp

#include "pch.h"
#include "Dll3.h"

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

Dll3.h

#pragma once

using namespace std;

extern "C" __declspec(dllexport) int testFunc(int a, int b);

dllmain.cpp

#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;
}

pch.h

#pragma once

#include "targetver.h"

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#endif

// Windows Header Files:
#include <windows.h>

pch.cpp

#include "pch.h"

我将构建目标设置为x64,成功导出DLL文件,没有任何错误或警告。

Unity Project

我将Dll3.dll文件放到了Assets/文件夹中。起初,我在Assets/Plugins/得到了它,但我发现它并不重要。

test.cs中

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;

public class test : MonoBehaviour {

    // Dll import according to Unity Manual
    #if UNITY_IPHONE || UNITY_XBOX360
    [DllImport ("__Internal")]
    #else
    [DllImport ("Dll3")]
    #endif
    private static extern int testFunc (int a, int b);

    // Use this for initialization
    void Start () {
        int a = 1;
        int b = 2;
        int c = testFunc (a, b);
        Debug.Log (c.ToString ());
    }

    // Update is called once per frame
    void Update () {

    }
}

然后我创建了一个空的游戏对象,将此脚本分配给它,编译并运行。它编译时没有任何错误或警告,但在运行时(在编辑器中),我得到了这个:

Failed to load 'Assets/Dll3.dll' with error 'This operation is only valid in the context of an app container.', GetDllDirectory returned ''. If GetDllDirectory returned non empty path, check that you're using SetDirectoryDll correctly.
Failed to load 'Assets/Dll3.dll' with error 'This operation is only valid in the context of an app container.', GetDllDirectory returned ''. If GetDllDirectory returned non empty path, check that you're using SetDirectoryDll correctly.
DllNotFoundException: Assets/Dll3.dll
    test.Start () (at Assets/test.cs:18)

任何人都可以指出我在做错的地方吗?我习惯于Unix(OSX / Linux)环境和Windows非常不合适。我完全不了解VS DLL项目的概念。我将不胜感激任何帮助。谢谢

1 个答案:

答案 0 :(得分:1)

是的,从一开始就是正确的。我只需要在Visual Studio Simulator中运行它,作为我桌面上的Store App或将其部署到我的开发平板电脑。它不在Unity编辑器中运行 - 我真是个傻瓜: - )