I do this precise operation in my KurtMaster2D game, on Android, iOS, MacOSX and Windows.
Here is my code to allocate and pin the texture, and pass the array of bytes into native code.
Native code then renders to this buffer, and when it comes back I marshal back into a Texture2D for display.
public static void PinTextureAndCallNativeRenderColor( Texture2D t2d, int span, bool clean = false)
{
if (clean || (pixels == null) || (span != pixelSpan))
{
pixelSpan = span;
pixels = new Color32[ pixelSpan * pixelSpan];
}
GCHandle handle = GCHandle.Alloc(pixels, GCHandleType.Pinned);
try
{
dispatcher1_rendercolor( handle.AddrOfPinnedObject(), span, 0);
}
finally
{
if (handle.IsAllocated)
{
handle.Free ();
}
}
t2d.SetPixels32( pixels);
t2d.Apply();
}
Here is the interop signature for that native method:
[DllImport ("__Internal")]
private static extern void dispatcher1_rendercolor(
System.IntPtr pixels, int span, int flags);
And finally the actual native C code signature is (actually, here’s the entire native C function):
DECORATE_FOR_DLL void dispatcher1_rendercolor( void *rgbpixels, int span, int flags)
{
if (wbi.workbuf_p)
{
int w = wbi.maxx;
int h = wbi.maxy;
unsigned char *ucptr = (unsigned char *)wbi.workbuf_p;
unsigned int *uptr = (unsigned int *)rgbpixels;
int i, j;
for (j = 0; j < h; j++)
{
for (i = 0; i < w; i++)
{
*uptr++ = kpios_last_palette_256_rgba[ *ucptr++];
}
uptr += (span - w);
}
}
else
{ // this simulates noise from a blank TV channel
int w = span;
int h = span;
int i, j;
unsigned char *cptr = (unsigned char*)rgbpixels;
for (j = 0; j < h; j++)
{
for (i = 0; i < w; i++)
{
*cptr++ = rand();
*cptr++ = rand();
*cptr++ = (rand() & 0xff) / 4;
*cptr++ = 255;
}
cptr += 4 * (span - w);
}
}
}
NOTE: the “engines” inside this game collection are mostly 8-bit color, hence the palette expansion you see.
NOTE: this same code runs on all targets: iOS 32bit, 64bit, Android 32bit, 64bit, MacOSX 64bit, and Windows 32-bit.
And you can see it all in action here in the final product:
Appstores:
Apple iTunes: KurtMaster2D on the App Store
Google Play: https://play.google.com/store/apps/details?id=com.plbm.plbm1