简体   繁体   English

如何从C#(Unity)将参数传递给本机插件?

[英]How do I pass parameters to a native plugin from C#(Unity)?

C++ code: C ++代码:

#include "stdafx.h"

class myClass
 {
  __declspec(dllexport) float addMyNum(float a)
   {
     return(a);
   }
};

The above code is compiled into Trail.dll and placed in the Unity project's Plugin folder. 上面的代码被编译到Trail.dll中,并放置在Unity项目的Plugin文件夹中。

Unity C# code: Unity C#代码:

using UnityEngine;
using System.Runtime.InteropServices;


public class ndstryscript : MonoBehaviour {

 [DllImport("Trial", EntryPoint = "?addMyNum@myClass@@AEAAMPEAM@Z")]

 private static extern float addMyNum(float a);

 void Start ()
  {
    float b = addMyNum(20);
    Debug.Log(b);
  }

}

在此处输入图片说明

The expected output is 20 but I'm always getting 0. Could someone help me resolve this? 预期的输出为20,但我始终为0。有人可以帮我解决这个问题吗?

On the C++ side, you have to move the addMyNum function out of the myClass class. 在C ++方面,您必须将addMyNum函数移出myClass类。 This should fix your function return 0 issue. 这应该解决您的函数返回0问题。

Another thing that can cause this issue is the parameter amount not matching between the C++ and C# functions. 可能导致此问题的另一件事是C ++和C#函数之间的参数数量不匹配。 For example, when you have this on C++ side: 例如,当您在C ++方面拥有此功能时:

DLLExport int add(int num1, int num2){ return ...}

but this on the C# side: 但这在C#方面:

[DllImport("FirstDLL")]
public static extern int add(int num1);

You get undefined behavior with this The result will be random because the function on the C# side has one parameter while the one from C++ has two. 您将获得不确定的行为结果将是随机的,因为C#端的函数有一个参数,而C ++中的一个有两个参数。


Unrelated but using EntryPoint = "?addMyNum@myClass@@AEAAMPEAM@Z" really looks weird. 无关,但使用EntryPoint = "?addMyNum@myClass@@AEAAMPEAM@Z"真的很奇怪。 Sometimes it's needed but other times, it's not as you will have to find the function name and match it with what you need to call on the C# side. 有时是需要的,但有时却不是,因为您不必查找函数名称并将其与需要在C#端调用的名称匹配。 You can just put your C++ function inside extern "C" and it will make sure that the compiler does not change the function name. 您可以将C ++函数放在extern "C" ,这样可以确保编译器不会更改函数名称。

extern "C"
{
    __declspec(dllexport) float addMyNum(float a)
    {
        return(a);
    }
}

Then your C# side: 然后您的C#端:

[DllImport("Trial")]
public static extern float addMyNum(float a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM