Skip to content

Instantly share code, notes, and snippets.

@bachue
Created January 3, 2020 07:35
Show Gist options
  • Select an option

  • Save bachue/efa5a99fbd39e64dc0a4fe5ad69807fb to your computer and use it in GitHub Desktop.

Select an option

Save bachue/efa5a99fbd39e64dc0a4fe5ad69807fb to your computer and use it in GitHub Desktop.

Revisions

  1. bachue created this gist Jan 3, 2020.
    21 changes: 21 additions & 0 deletions abc.h
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    #ifndef __ABC____H
    #define __ABC____H

    /* Generated with cbindgen:0.12.0 */

    #include <stdarg.h>
    #include <stdbool.h>
    #include <stdint.h>
    #include <stdlib.h>

    #ifdef __cplusplus
    extern "C" {
    #endif // __cplusplus

    bool read_all_from_file(FILE *file);

    #ifdef __cplusplus
    } // extern "C"
    #endif // __cplusplus

    #endif /* __ABC____H */
    26 changes: 26 additions & 0 deletions lib.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    use libc::{FILE, fread, feof, ferror};

    #[no_mangle]
    pub extern "C" fn read_all_from_file(file: *mut FILE) -> bool {
    let mut buf = [0u8; 1 << 12];
    let mut r = 0;
    println!("fread() starts");
    while unsafe { feof(file) } == 0 {
    let hr = unsafe { fread(buf.as_mut_ptr().cast(), 1, 1 << 12, file) };
    println!("fread() got {} bytes", hr);
    if hr == 0 {
    if unsafe { feof(file) } != 0 {
    println!("feof(file) returns non-zero");
    break;
    }
    if unsafe { ferror(file) } != 0 {
    println!("ferror() returns non-zero");
    return false;
    }
    } else {
    r += hr;
    }
    }
    println!("fread() got {} bytes totally", r);
    true
    }
    30 changes: 30 additions & 0 deletions main.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    #include <stdio.h>
    #include "abc.h"
    #pragma comment(lib, "abc.dll.lib")

    int main(int argc, char* argv[]) {
    if (argc != 2) {
    fprintf(stderr, "Usage: %s PATH\n", argv[0]);
    return 1;
    }

    errno_t err;
    FILE *file;
    err = fopen_s(&file, argv[1], "rb");

    if (err) {
    fprintf(stderr, "Error for _wfopen_s()\n");
    return 2;
    }

    printf("calling read_all_from_file()\n");
    if (read_all_from_file(file)) {
    printf("OK\n");
    }
    else {
    printf("Error\n");
    }

    fclose(file);
    return 0;
    }