unity 调用C++ dll 操作升级套娃函数调用

之前一直以为C++生成dll,在unity中调用时要把传出去的值设置在主函数中,以参数或反回值的形式。

当然在DLL工程中可以说没有主函数,那个可以运行一个函数,其会调用其他函数从而一直调其他相关函数。

那问题是在层级是二或三------时被调用的那个函数的计算结果怎么能生成dll在unity用呢??

方案一,将需要的计算结果通过--------------在运行主函数时以参数或返回值的结果呈现肯定可以。

unity 调用C++ dll_unity调用c++封装的dll 非常卡_天人合一peng的博客-CSDN博客

但问题有时c++工程比较庞大,真的很难将需要的计结果直接以参数或返回值以主函数为载体呈现。

于是,我想那不管了,直接从想要计算结果的那导出函数和计算结果可以吗?如果可行那就简单多了。

方案二,通过测试可行。

C++工程

所有文件如下

 Fun01.h

#pragma once
#include <iostream>
int calAdd(int a, int b);

Fun01.cpp

#include <iostream>


extern "C" __declspec(dllexport)
int calMul(int a, int b, int* ptr)
{
	int arrayValue[2] = { 4, 8};

	memcpy(ptr, arrayValue, sizeof(int)*2);
	return a * b;
}


int calAdd(int a, int b)
{
	int c = calMul(a, b, &a);
	
	std::cout << "hello" << std::endl;
	return a + b;
}

DllU3d01.cpp

// DllU3d01.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>

#include "Fun01.h"
int main()
{

    //std::cout << "Hello World!\n";
    std::cout << calAdd(4, 5) << std::endl;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单

// 入门使用技巧: 
//   1. 使用解决方案资源管理器窗口添加/管理文件
//   2. 使用团队资源管理器窗口连接到源代码管理
//   3. 使用输出窗口查看生成输出和其他消息
//   4. 使用错误列表窗口查看错误
//   5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
//   6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件

现在验证如果不在主函数传值,直接从calMul函数导出可以不?

生成dll

 unity工程添加脚本

 useDll.cs

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


public class useDll : MonoBehaviour
{
    [DllImport("D:\\BUFFER\\Unity\\DLLProject01\\Assets\\VSDLL\\DllU3d01")]
    static extern int calMul(int a, int b, int[] x);

    private int[] x = new int[2];
    int vsValue = 0;

    // Start is called before the first frame update
    void Start()
    {
        vsValue = calMul(23, 11, x);
        print(vsValue);
        print("-------------------************----------------");

        for (int i = 0; i < 2; i++)
        {
            print(x[i]);
        }
        //Console.WriteLine("hello");

    }

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

将上面VS生成的dll放在到unity Assets下的VSDLL文件夹中

 在这种情况下,可以直接写

[DllImport("DllU3d01")]

双引号是dll的名字,只是不写后缀

运行程序

 还真可以。

猜你喜欢

转载自blog.csdn.net/moonlightpeng/article/details/131741064