首页 文章

Unity3D调用外部DLL

提问于
浏览
1

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

我试图添加一个DLL与我自己的低级别的东西 Windows Store 目标 .

我试图以这种方式访问的东西并不重要,我被困在 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项目

我将 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 回答

  • 1

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

相关问题