简体   繁体   中英

Integration between C++ DLL and C# Unity

I'm having issues with C++ Dll Integration with Unity. I found some code in the web (link at the end of article) but it doesn't work.

This is my C++ DLL code (I want to send unity a structure with some points):

struct Pontos {
int i;
float f;
};
Pontos **pontos;
DllExport bool SetPoints(Pontos *** a, int *i)
{

    pontos = new Pontos*[4];
    for (int j = 0; j < 4; j++) {
            pontos[j] = new Pontos; // Actually create each object.
            pontos[j]->i = j;
            pontos[j]->f = (float)j;
        }
        *a = pontos;
        *i = 4;
        return true;
    }

From the unity code, I get the following error:

No MonoBehaviour scripts in the file, or their names do not match the file name

I don't know what this means. Here I try to get those points and save them in c#:

[DllImport("dll")]
private static extern bool SetPoints(out IntPtr ptrResultVerts, out int resultVertLength);
public struct Pontos
{
    int i;
    float f;
};     
void Start()
{ 
    IntPtr ptrNativeData = IntPtr.Zero;
    int itemsLength = 0;

    bool success = SetPoints(out ptrNativeData, out itemsLength);
    if (!success)
    {
        return;
    }

    Pontos[] SArray = new Pontos[itemsLength];  // Where the final data will be stored.
    IntPtr[] SPointers = new IntPtr[itemsLength];

    Debug.Log("Length: " + itemsLength); // Works!
    Marshal.Copy(ptrNativeData, SPointers, 0, itemsLength); // Seems not to work.

    for (int i = 0; i < itemsLength; i++)
    {
        Debug.Log("Pointer: " + SPointers[i]);
        SArray[i] = (Pontos)Marshal.PtrToStructure(SPointers[i], typeof(Pontos));
    }

I got this code from Can't marshal array of stucts from C++ to C# in Unity .

You must import the dll specifying the calling convention

[DllImport("MyDLL.dll", CallingConvention = CallingConvention.Cdecl)]

I don't think the error

No MonoBehaviour scripts in the file, or their names do not match the file name

has anything to do with your code. Check your class name and your script name. Do they correspond?

Finally, I'm not sure about the out modifier in the method signature as I never have to deal with triple pointers on the C++ side. If your goal is to fill an array of Pontos structures than you shouldn't need it.

See also Pass structure (or class) from C++ dll to C# (Unity 3D)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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