Unity3D 调用VC和Csharp dll

1.C#封装的dll

现在vs中创建一个类,里面只要写一个简单的静态类和静态方法就可以了,如下:

namespace pnsd
{
    public static class pn
    {
        public static string getName(string name)
        {
            return name;
        }
    }
}

然后编译成dll文件,名字为pnsd.dll

2.在unity中使用自定义的C#封装的dll组件 

在unity中创建一个Plugins文件夹,所有的外部引用的dll组件必须要放在这个文件下,才能被using

在C#脚本中用这个dll:

using UnityEngine;
using System.Collections;
using pnsd;//不是dll文件的名字,而是namespace的名字
public class test:MonoBehaviour 
{
  void Start()
   {
    string name = pn.getName("pnsd");//类名.方法名
    Debug.Log(name);//输出结果
  }
}

3. 首先用vc建立一个dll工程

4. 然后在里面建立一个testunity.h文件。内容如下

extern "C" int _declspec(dllexport)testunity(); // 定义道出接口

保存,ok,在建立一个testunity.cpp,代码如下:

#include "testunity.h"
int testunity()
{
   return 0;//这是函数,里面可以写你想要实现的任何功能
}

然后编译、组建。就生成了testunity.dll文件。

然后再把这个文件放在你的unity工程的assert的Plugins(如果没有这个文件,那你就要新建了)

然后在unity里面新建C#脚本文件dlltest。代码如下

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
public class dlltest : MonoBehaviour 
{ [DllImport (
"testunity")] private static extern int testunity(); // Use this for initialization int i=testunity(); void Start () { print(i); } // Update is called once per frame void Update () { } }

然后再把这个文件在unity里面拖到camera里面就ok了。

然后运行,就可以实现效果了哈。

《如果是C#封装的dll,就用 using的方式引用,如果是C++的dll,就DllImport[".dll"]的方式来添加对dll的引用》

 

 

posted on 2014-12-05 23:58  小魔一剑  阅读(899)  评论(0编辑  收藏  举报