Skip to content

Instantly share code, notes, and snippets.

@zed

zed/.gitignore Secret

Created February 12, 2011 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zed/6b46c1237cca16ef30c1 to your computer and use it in GitHub Desktop.
Save zed/6b46c1237cca16ef30c1 to your computer and use it in GitHub Desktop.
pass c-array via pipe
#
/echo_vertices
import struct, sys
from subprocess import Popen, PIPE
def pack(vertices, n):
yield struct.pack('i', n)
s = struct.Struct('i f f')
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 = struct.unpack('iff', out)
assert index == (n-1) and int(x) == n and int(y) == (n+1)
if __name__ == '__main__':
main()
/** 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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment