Unity调用C++动态链接库(DLL)或者C#类库

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Exclaiming/article/details/86077965

一、Unity调用C++动态链接库

1.新建DLL

2.新建头文件及源文件CPP

(头文件U3DTest.h)

#if defined (EXPORTBUILD)
# define _DLLExport __declspec (dllexport)
# else
# define _DLLExport __declspec (dllimport)
#endif


extern "C" int _DLLExport Add(int x, int y);

(源文件U3DTestDLL.cpp)

#include"U3DTest.h"//引入头文件

int Add(int a, int b)

{
	return (a + b);
}

3.运行导出DLL

4.在程序根目录下找到生成的DLL复制到Unity Asset下面的Plugins里面,或者直接将VS的生成目录改到unity的Plugins下面,如下图所示,如果没有该文件夹,自己创建一个即可,至此VS里面的工作已经做完,下一步打开unity,在unity里面调用对应的函数即可;

5.打开unity,新建脚本,注意名词空间的引用 using System.Runtime.InteropServices;

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
public class NewBehaviourScript : MonoBehaviour
{
    [DllImport("U3DDll")]
    private static extern int Add(int x,int y);
	// Use this for initialization
	void Start ()
    {
        print(Add(3,5));//调用Add函数求两个数的和,并在控制台打印出来
	}
	
}

6.返回控制台查看结果是否正确

二、unity调用C#类库

1.新建C#类库,目前unity只支持.NET Framework3.5或者3.5以下,因此需将目标框架更改为3.5或以下

2.新建类Calcuate以及函数Add,注意函数必须定义为公有静态的

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestSuccessful
{
    public class Calcuate
    {
        public static int Add(int a, int b)
        {
            return (a + b);
        }
    }
}

3.启动生成DLL,并将生成的DLL复制到Unity的Plugins里面,或者直接将输出路径改到Plugins,运行即可

4.Unity中调用C#类库很简单,只需将类库的名词空间引用即可,在调用函数时用类的名词可以找到类里面的公有静态函数

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//using System.Runtime.InteropServices;
using TestSuccessful;//对应类库名词空间
public class NewBehaviourScript : MonoBehaviour
{
    //[DllImport("U3DDll")]
    //private static extern int Add(int x,int y);
	// Use this for initialization
	void Start ()
    {
        //print(Add(3,5));//调用C++ DLL  Add函数求两个数的和,并在控制台打印出来

        print(Calcuate.Add(100,300));//用类名调用C# 类库  Add函数求两个数的和,并在控制台打印出来
    }
	
}

5.运行测试结果

猜你喜欢

转载自blog.csdn.net/Exclaiming/article/details/86077965