Created
February 25, 2014 12:01
-
-
Save hacha/9207616 to your computer and use it in GitHub Desktop.
UnityのNativePluginで、Unity側のC#スクリプトからbyte配列を渡したり、プラグイン側からbyte配列を受け取る方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Runtime.InteropServices; | |
using System.Text; | |
using System.IO; | |
using System; | |
public class Binding { | |
[DllImport("__Internal")] | |
private static extern bool Test(byte[] ptrSrc, int srcLength, ref IntPtr ptrDest, ref int destLength); | |
[DllImport("__Internal")] | |
private static extern void Free_Memory(ref IntPtr ptrData); | |
public static void Test () | |
{ | |
if (Application.platform == RuntimePlatform.IPhonePlayer) { | |
MemoryStream ms = new MemoryStream(); | |
BinaryWriter bw = new BinaryWriter(ms); | |
// TODO write | |
bw.Flush(); | |
byte[] srcData = ms.ToArray(); | |
bw.Close(); | |
ms.Close(); | |
IntPtr ptrResult = IntPtr.Zero; | |
int resultLength = 0; | |
bool success = Test(srcData, srcData.Length, ref ptrResult, ref resultLength); | |
byte[] result = null; | |
if (success) { | |
result = new byte[resultLength]; | |
Marshal.Copy(ptrResult, result, 0, resultLength); | |
Free_Memory (ref ptrResult); | |
ms = new MemoryStream(result); | |
long length = ms.Length; | |
BinaryReader br = new BinaryReader(ms); | |
// TODO read | |
br.Close(); | |
ms.Close(); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bool Test (const char** ptrSrc, const int srcLength, char** ptrDest, int* destLength) | |
{ | |
NSData *src = [NSData dataWithBytes:(const void *)ptrSrc length:(sizeof(unsigned char) * srcLength)]; | |
// TODO read | |
NSMutableData *result = [[[NSMutableData alloc] initWithLength:0] autorelease]; | |
// TODO write | |
int test = 123; | |
[result appendData:[NSData dataWithBytes:&test length:sizeof(test)]]; | |
NSUInteger length = [result length]; | |
*ptrDest = (char*)malloc(length); | |
memcpy(*ptrDest, [result bytes], length); | |
*destLength = length; | |
return true; | |
} | |
void Free_Memory (char** ptrDest) | |
{ | |
free(*ptrDest); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment