1. 程式人生 > >unity-呼叫動態庫dll-windows篇

unity-呼叫動態庫dll-windows篇

1、生成64位的dll

  1. 用vs新建個工程,隨便寫個函式
    NaviteCode.h

        #ifndef __NativeCode_H__
        #define __NativeCode_H__
    
        #ifndef EXPORT_DLL
        #define EXPORT_DLL __declspec(dllexport) //匯出dll宣告
        #endif
    
        extern "C" {
            EXPORT_DLL int MyAddFunc(int _a, int _b);
        }
        #endif

    NaviteCode.cpp

    
    #include "NaviteCode.h"
    extern "C" { int MyAddFunc(int _a, int _b) { return _a + _b; } }

    extern “C” 就不用說明了吧,指定c編譯器編譯,後面打Android的so庫也是用相同的程式碼

  2. 修改vs匯出配置,匯出為64位Release的dll(應為用的是unity是64位的)

    這裡寫圖片描述

    這裡寫圖片描述

  3. 生成,就出來了這個 NativeCode.dll

2、拷貝 NativeCode.dll 到unity工程中

  • unity存放動態庫是由規則的不同平臺放置的目錄不同,官網傳送門,點我

  • 所以按照規則,把 NativeCode.dll

    放入 Assets\Plugins\x86_64 目錄中

3、c#中呼叫一下,隨便create個c#掛在場景的物件中

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices; //DllImport需要的namespace

public class testDll : MonoBehaviour {

    [DllImport("NativeCode")] //這裡就是呼叫的dll名字
    public static extern int MyAddFunc(int
x, int y); // Use this for initialization void Start () { int ret = MyAddFunc(200, 200); Debug.LogFormat("--- ret:{0}", ret); } }

done
這裡寫圖片描述