secret
Last active

pass c-array via pipe

  • Download Gist
.gitignore
1 2
#
/echo_vertices
__main__.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
import struct, sys
 
from subprocess import Popen, PIPE
 
S = struct.Struct('i f f')
 
def pack(vertices, n):
yield struct.pack('i', n)
for v in vertices:
yield S.pack(*v)
 
def main():
try: n = int(sys.argv[1])
except IndexError:
n = 100
vertices = ((i,i+1,i+2) for i in range(n))
 
p = Popen(["./echo_vertices", "random", "arg"], stdin=PIPE, stdout=PIPE)
out, _ = p.communicate(b''.join(pack(vertices, n)))
 
index, x, y = S.unpack(out)
assert index == (n-1) and int(x) == n and int(y) == (n+1)
 
if __name__ == '__main__':
main()
echo_vertices.c
C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/** http://stackoverflow.com/questions/4979421/subprocess-popen-invalid-argument-broken-pipe-while-comunicating-to-c-program */
#include<stdio.h>
#include<stdlib.h>
 
typedef struct {
int index;
float x;
float y;
} vertex;
 
int main(int argc, char* argv[]) {
int i;
vertex* VV;
int n = 0;
fread(&n, sizeof(int), 1, stdin);
VV =(vertex*) malloc(sizeof(vertex)*n);
fread(VV,sizeof(vertex),n,stdin);
 
/* write the last vertex */
fwrite(&VV[n-1], sizeof(vertex), 1, stdout);
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.