有几种可能性:
https://stackoverflow.com/questions/49793560/build-c-plugin-for-unity?rq=1
我检查过后,发现不是上面两种情况。那基本上就是缺少必要的dll文件。网上很多人推荐用 Dependency Walker
,但是这个有些过时且不实用,这里墙裂推荐Dependencies。下载这个,把你生成的dll拖进去,基本上就能发现问题了。我的情况是这样的:
从专门下载dll文件的网站上下载并放到System32文件夹中就好了。
解决完这个问题后,我还遇到了Unity闪退的问题,心态崩了一天,最后的原因竟然是我C++代码里的路径写成相对路径了,有一个文件无法加载进来,改成绝对路径就好了。。。
另外简单总结一下Unity导入dll步骤:
VS中新建DLL(Universal Windows)工程,用得到的函数前面加extern "C" __declspec(dllexport)
这里大家可以建个工程自己测试一下:
开发环境:VS2019, X64
//MyDLL.h
#pragma once
#include <iostream>
#define EXPORT_DLL __declspec(dllexport) //导出dll声明
extern "C"
{
EXPORT_DLL int MyAddFunc(int _a, int _b);
}
//MyDLL.cpp
#include "pch.h"
#include "MyDLL.h"
int MyAddFunc(int _a, int _b)
{
return _a + _b;
}
Unity中新建一个脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;//必须加上这个!
public class DLL : MonoBehaviour
{
[DllImport("MyDLL")]
public static extern int MyAddFunc(int a, int b);
// Start is called before the first frame update
void Start()
{
Debug.Log(MyAddFunc(2, 3));
}
// Update is called once per frame
void Update()
{
}
}