Converting IntPtr (CPU buffer representing Y channel) to AndroidJavaObject without copy

When calling AcquireCameraImageBytes to retrieve an CameraImageBytes instance and the underlying Y IntPtr buffer, I need to pass that IntPtr to my own AAR library which takes a ByteBuffer as argument. I could not find a way of converting the IntPtr to an AndroidJavaObject reference which would allow me to pass it to my method.

using (GoogleARCore.CameraImageBytes image = GoogleARCore.Frame.CameraImage.AcquireCameraImageBytes())
{
    if (!image.IsAvailable)
    {
        return;
    }

    int width = image.Width;
    int height = image.Height;
    IntPtr yPixelBuffer = image.Y;

    using (AndroidJavaClass utilsClass = new AndroidJavaClass("com.mypackage.MyClassUtils"))
    {
        utilsClass.CallStatic("setCurrentBuffer", yPixelBuffer, width, height); // <-- Need to pass a AndroidJavaObject here but no way to just pass the ByteBuffer
    }
}

the Java method implementation:

public class MyClassUtils {
    public static final void setCurrentBuffer(
                                              ByteBuffer buffer,
                                              int width,
                                              int height) {
}

Is there any way to convert the IntPtr to its underlying ByteBuffer reference ?

The IntPtr is actually backed by a C unsigned char*, i.e. a raw pointer to the Y channel. The most efficient way to do this would be to jump through JNI (in C) and create a ByteBuffer using the JNI NewDirectByteBuffer.

Alternatively, you can always use Marshal.Copy to convert an IntPtr into a C# byte[ ], and then do normal Unity things to convert that to Java objects. That involves a bunch of copies of the image which may impact performance, though.

The IntPtr is actually backed by a C unsigned char* @chaosemer thanks a lot for this, I really thought it was pointing to the address of a ByteBuffer object, my bad. I don’t want to create a new ByteBuffer with NewDirectByteBuffer but to directly pass the IntPtr to my .so C++ library and use the pointer to unsigned char* there. I reckon I will have to do that. Thanks again.