Search Unity

Sending a NativeArray to be modified in a C++ Native Plugin

Discussion in 'Entity Component System' started by chanon81, Nov 23, 2018.

  1. chanon81

    chanon81

    Joined:
    Oct 6, 2015
    Posts:
    168
    Hi!,

    I was wondering if it is possible to send a NativeArray pointer to a C++ Native Plugin to be modified. What is the fastest way to do this? Since it is a NativeArray, I was wondering if there is a way that avoids any Marshalling/Copying.

    This would be for an array of bytes.
     
  2. chanon81

    chanon81

    Joined:
    Oct 6, 2015
    Posts:
    168
  3. chanon81

    chanon81

    Joined:
    Oct 6, 2015
    Posts:
    168
    OK, here it is:

    Code (C++):
    1.  
    2. extern "C" {
    3.    void UNITY_EXPORT SendBytes(void *bytes) {
    4.        unsigned char *ptr = (unsigned char *)bytes;
    5.        // do something
    6.    }
    7. }
    8.  
    Code (CSharp):
    1.  
    2. [DllImport("libraryName")]
    3. unsafe public static extern void SendBytes(void* bytes);
    4.  
    5. // usage
    6. void SomeFunction(NativeArray<byte> nativeByteArray) {
    7.    unsafe {
    8.       void* ptr = NativeArrayUnsafeUtility.GetUnsafePtr(nativeByteArray);
    9.       SendBytes(ptr);
    10.    }
    11. }
    12.  
     
    Last edited: Nov 23, 2018
    Sena_Translimit and XsongyangX like this.
  4. julian-moschuering

    julian-moschuering

    Joined:
    Apr 15, 2014
    Posts:
    529
    GetUnsafePtr/GetUnsafeReadOnlyPtr extension methods of NativeArray.
     
  5. zagrizzl

    zagrizzl

    Joined:
    Jul 17, 2019
    Posts:
    7
    note that you must also set the saftey handle
    NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref arr, AtomicSafetyHandle.Create());