Unity3D调用自定义C++DLL

    上篇文章说到了Unity调用Windows Dll库的方法

     最近需求又升级了,需要调用自定义的一个Fly.dll飞行库,进行轨迹获取

     所以研究研究Unity调用自定义dll的 方法,Unity3D端还是一致,需要声明需要调用的函数

     首先创建C++ DLL库

            新建一个test.h,在其中添加如下代码:

#pragma once

#define _DLLExport extern "C" __declspec (dllexport)  
_DLLExport int AddNum()
{
	int a = 1;
	int b = 2;
	int c = a + b;
	return c;
}

   在dllmain.cpp 包含头文件test.h,因为未包含的头文件将不会进行编译

   配置成x64位relase版

   编译通过

   找到生成的TestDLL.dll拖入unity3d工程中

这时dll库已经成功引入了,下一步,就是C#端的调用

声明AddSum函数

public static class Customize
{

    [DllImport("TestDLL")]
    public static extern int AddNum(
    );
}

进行调用源码如下:

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

public static class Customize
{

    [DllImport("TestDLL")]
    public static extern void AddNum(
    );
}

    public class TestCustomize : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Test();
    }


    // 测试代码
    void Test()
    {
        try
        {
            Debug.Log(Customize.AddNum());
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
            Debug.Log(e.StackTrace);
        }
    }

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

运行结果:

  这样我们就成功实现dll的简单调用

  二、复杂调用(待完成)

  dll导出函数里包含结构体参数、数组参数等的实现,

发布了69 篇原创文章 · 获赞 69 · 访问量 8420

猜你喜欢

转载自blog.csdn.net/q943520218/article/details/103373965
今日推荐