Hi, I have a problem about iOS native plugin.
I wanna send byte[ ] value to native code.
But, I don’t know how to make native method.
I make a plugin method like this.
[DllImport ("__Internal")]
private static extern void _SendPhoto(byte[] data);
Then, use like this.
Texture2D tex = new Texture2D(100, 100);
tex.ReadPixels(new Rect(0, 0, 100, 100), 0, 0);
byte[] buffer = tex.EncodeToPNG();
_SendPhoto(buffer);
and, how to I make native code?
I don’t know what kind of argument is proper.
I try to like below code, but it doesn’t work.
extern "C"
{
void _SendPhoto(void * data) {}
}
please, help me.
thanks.
Look at the Marshal class and the MarshalAs attribute, they are used to interface datatransfers with native code
I prefer the GCHandle class.
You can do something like this:
GCHandle handle = GCHandle.Alloc(myByteArray, GCHandleType.Pinned);
MyPluginFunction(myByteArray.Length, handle.AddrOfPinnedObject());
handle.Free();
Then in Native Code
public void MyPluginFunction(int length, byte* byteArrayPtr)
{
for(int i = 0; i < length; i++)
{
//do something with byteArrayPtr here
byteArrayPtr++;
}
}
I’ve even used that method to pass around arrays of structs with variable sized image data.
// Ntero
Thank for answering.
I declare a method
[DllImport ("__Internal")]
private static extern void _SendPhoto(int length, System.IntPtr byteArrPtr);
is this right?
And in native code(Objective-C), receive pointer argument
void _SendPhoto(int length, Byte * byteArrPtr)
is this right?
Thanks:)
Yeah, that’d work, I’m doing something similar. You can even do Pointer Math with the IntPtr class, so you can reference subsets of the array so long as you pin it down. Keep in mind you are no longer sending the data to the plugin, but just letting the plugin know where the data is stored, so it can access it itself.
They reduce the amount of data transfer required as you can just pass where the data is instead of passing all the data itself.
The reason for the GCHandle is that without it the Garbage Collector is allowed to destroy and relocate objects in memory. That function basically means that no-one can move your object while you are accessing it. This also means you need to guarantee you call free or else you’ll find yourself possibly with a leak. Also, I find it’s an easy way to get an IntPtr to the data.
Hello.
I am writing a plugin like this, but NSData is always nil.
Is it wrong?
I tried both below(ary is Byte*, length is int):
NSData* dat = [NSData dataWithBytes:ary length:length];
or
NSData* dat = [[NSData alloc] initWithBytes:byteArrPtr length:length];
please help me.
I use: Unity 2017.1, XCode 9.0 beta5, iOS11.