Skip to content

Instantly share code, notes, and snippets.

@hacha
Created February 25, 2014 12:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hacha/9207616 to your computer and use it in GitHub Desktop.
Save hacha/9207616 to your computer and use it in GitHub Desktop.
UnityのNativePluginで、Unity側のC#スクリプトからbyte配列を渡したり、プラグイン側からbyte配列を受け取る方法
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();
}
}
}
}
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