LoginSignup
3
6

More than 5 years have passed since last update.

Cからdouble型の配列をバイナリにしてUDPで送り、unityのBitConverterで受け取る

Last updated at Posted at 2015-11-05

Cから [0, 1, 0.0005, -0.0009] という配列をUDPで送り、Unity側でdouble配列に戻す。

送信(C)側

udp.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>

#define INTERVAL_TIME 1

void udpSend (char* address, int port);
int port = 20001;
char addr[] = "0.0.0.0";
double data[] = { 0, 1, 0.0005, -0.0009 };

int main()
{
    udpSend(addr,port);
    return 0;
}

void udpSend(char* address, int port)
{
    int udp = socket(AF_INET,SOCK_DGRAM,0);
    struct sockaddr_in addr;
    struct hostent *host;

    memset(&addr, 0, sizeof(addr));
    host = gethostbyname(address);
    memcpy(host->h_addr, &addr.sin_addr, host->h_length);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);

    while (1)
    {
        sendto(udp, (unsigned char*) data, sizeof data, 0, (struct sockaddr *)&addr, sizeof(addr));
        sleep(INTERVAL_TIME);
    }

    close(udp);
}

コンパイルして送信開始。

$ gcc udp.c
$ ./a.put

受信(Unity)側。適当なGameObjectにくっつけておく

UDPReceive.cs
using System;
using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Threading;

public class UDPReceive : MonoBehaviour
{
    private const int DATA_LENGTH = 4;
    private const int DOUBLE_LENGTH = 8;
    private UdpClient udp;
    private Thread thread;
    private byte[] data;
    private double[] result = new double[DATA_LENGTH];

    void Start ()
    {
        udp = new UdpClient (20001);
        thread = new Thread (new ThreadStart (threadWork));
        thread.Start (); 
    }

    void Update()
    {
        if (data != null)
        {
            Debug.LogFormat ("{0}, {1}, {2}, {3}", result[0], result[1], result[2], result[3]);
        }
    }

    void OnApplicationQuit()
    {
        udp.Close ();
        thread.Abort ();
    }

    void threadWork()
    {
        while(true)
        {
            IPEndPoint remoteEP = null;
            data = udp.Receive(ref remoteEP);

            for (int i = 0; i<DATA_LENGTH; i++)
            {
                result[i] = BitConverter.ToDouble(data, i * DOUBLE_LENGTH);
            }
        }
    }
}
3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6