Passing byte array from C++ unmanaged dll to C# unity

后端 未结 2 1574
春和景丽
春和景丽 2020-12-06 15:37

I am trying to return the byte array from my unmanaged c++ dll back to c# unity. Thank you very much in advance for taking the time to help >< I\'m really new to DLL in u

相关标签:
2条回答
  • 2020-12-06 16:07

    There are many ways to return byte arrays from C# and below is one of them. The memory allocation and de-allocation are both done in C++. You must call the function to free the memory from C#. I made the example very simple so that you can easily integrate it in your current code.

    IntPtr is the key in this answer.

    C++:

    char* getByteArray() 
    {
        //Create your array(Allocate memory)
        char * arrayTest = new char[2];
    
        //Do something to the Array
        arrayTest[0]=3;
        arrayTest[1]=5;
    
        //Return it
        return arrayTest;
    }
    
    
    int freeMem(char* arrayPtr){
        delete[] arrayPtr;
        return 0;
    }
    

    C#:

    [DllImport("Test.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern IntPtr getByteArray();
    
    [DllImport("Test.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern int freeMem(IntPtr ptr);
    
    //Test
    void Start() {
     //Call and return the pointer
     IntPtr returnedPtr = getIntArray();
    
     //Create new Variable to Store the result
     byte[] returnedResult = new byte[2];
    
     //Copy from result pointer to the C# variable
     Marshal.Copy(returnedPtr, returnedResult, 0, 2);
    
     //Free native memory
     freeMem(returnedPtr);
    
     //The returned value is saved in the returnedResult variable
     byte val1 = returnedResult[0];
     byte val2 = returnedResult[1];
    }
    
    0 讨论(0)
  • 2020-12-06 16:07

    You could pass an extra parameter to the function, let's say another byte array, and then in the adjustBrightnesss function replace that myvector with that array. As far as i know you will get the array with the modified values

    0 讨论(0)
提交回复
热议问题