Created
September 28, 2011 10:33
-
-
Save nruth/1247601 to your computer and use it in GitHub Desktop.
RubyInline C experimentation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# run with Piece.xor_files 'output_filepath', ['infilepath1','infilepath2'] | |
require 'inline' | |
Class Piece | |
inline do |builder| | |
builder.include '<stdlib.h>' | |
builder.include '<stdio.h>' | |
builder.c_singleton <<-C_CODE | |
/* | |
rb_input_paths_array should be a ruby array of strings, | |
where the files referenced by path are of equal size | |
result_path should be the path of the desired result file | |
*/ | |
static int xor_files(char* result_path, VALUE rb_input_paths){ | |
int counter; | |
//set up files for reading | |
int input_files_length = RARRAY(rb_input_paths)->len; | |
FILE *input_files[input_files_length]; | |
for(counter=0; counter < input_files_length; counter++){ | |
char* path = RSTRING(rb_ary_shift(rb_input_paths))->ptr; | |
input_files[counter] = fopen(path, "rb"); | |
} | |
//read bytes and xor to output | |
int byte = 0; | |
FILE* output = fopen(result_path, "wb"); | |
while ((byte = fgetc(input_files[0])) != EOF) { | |
for (counter = 1; counter < input_files_length; counter++) { | |
byte ^= fgetc(input_files[counter]); | |
} | |
fputc(byte, output); | |
} | |
//clean up | |
for(counter=0; counter<input_files_length; counter++) { fclose(input_files[counter]); } | |
fclose(output); | |
return 0; | |
} | |
C_CODE | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# demonstrate ruby string -> C char[] param passing, and an array | |
# in irb run with | |
# require 'piece'; Piece.print_strings('foo', ['a','b']) | |
# hi | |
# foo | |
# a | |
# b | |
require 'inline' | |
Class Piece | |
inline do |builder| | |
builder.c_singleton <<-C_CODE | |
static int print_strings(VALUE rb_result_file_path, VALUE rb_input_file_paths){ | |
printf("hi\\n"); | |
printf("%s\\n", RSTRING(rb_result_file_path)->ptr); | |
int input_files = RARRAY(rb_input_file_paths)->len; | |
int counter; | |
for(counter=0; counter < input_files; counter++){ | |
printf("%s\\n", RSTRING(rb_ary_shift(rb_input_file_paths))->ptr); | |
} | |
return 0; | |
} | |
C_CODE | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment