質問

I was previously doing some number crunching and maintaining a gui in a c program. I would now like to do the number crunching in c, but send the data to python. Python will then create and update the gui based on the values sent.

Can anyone please point me in the direction of code to send a variable or array from a c program to a python program - then printing it in python?

Thank you

役に立ちましたか?

解決

Consider:

fifo.c

#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

int main (void)
{
    // Array to send
    int arr[] = {2,4,6,8};
    int len = 4;

    // Create FIFO
    char filename[] = "fifo.tmp";

    int s_fifo = mkfifo(filename, S_IRWXU);
    if (s_fifo != 0)
    {
        printf("mkfifo() error: %d\n", s_fifo);
        return -1;
    }

    FILE * wfd = fopen(filename, "w");
    if (wfd < 0)
    {
        printf("open() error: %d\n", wfd);
        return -1;
    }

    // Write to FIFO
    for (int i=0; i<len; i++)
    {
        int s_write = fprintf(wfd, "%d ", arr[i]);

        if (s_write < 0)
        {
            printf("fprintf() error: %d\n", s_write);
            break;
        }
    }

    // Close and delete FIFO
    fclose(wfd);
    unlink(filename);
}

fifo.py

filename = "fifo.tmp"

# Block until writer finishes...
with open(filename, 'r') as f:
    data = f.read()

# Split data into an array
array = [int(x) for x in data.split()]

print array

You'd first run the writer (c), which would block until the reader (python) opened and read the data. Then run the reader and both processes will terminate.

$ python fifo.py
[2, 4, 6, 8]

Notes:

  • Some better error handling will probably be beneficial (eg. if the named fifo exists because the c program didn't exit cleanly).
  • This is kind of inefficient, because you're converting the integer values to their string representation and sending that. I used it because the space delimiter is easy to work with, but you may consider sending the integer values themselves, and using a fixed-width parsing on the reader side.
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top