代码之家  ›  专栏  ›  技术社区  ›  Mark Elliot

将InputStream作为文件指针通过JNA传递给C代码

  •  4
  • Mark Elliot  · 技术社区  · 16 年前

    #include <stdio.h>
    void foo(FILE *bar);
    

    Java接口是什么样子的?我真正需要传给福的是什么?

    编辑:foo假设bar是fopen的结果,并调用类似fscanf的操作。

    2 回复  |  直到 16 年前
        1
  •  3
  •   Vinay Sajip    16 年前

    我不相信你能做到这一点-你没有简单的方法来访问 InputStream FileInputStream 很可能不会在stdio文件*上实现。要了解Java接口应该是什么样子,您需要发布更多关于 foo 功能-它的功能和使用方法。

    如果你不在乎 FILE * 实际上,您可以使用JNA编写代码来调用 fopen ,传入文件名和打开模式,并将结果作为不透明值传递给 ,例如(伪代码):

    path = "MyFile.txt";
    bar = Libc.fopen(path, "r");
    Libfoo.foo(bar);
    

    更新: 如果你需要一个字符串,其中包含的数据需要像文件一样处理,我认为你运气不好。不幸的是,标准C库不是建立在流抽象之上的,这意味着您不太可能实现您想要的,除非您可以打开看起来像文件名的文件,但会生成字符串数据;但是,咬紧牙关,将字符串保存到一个临时文件,然后用 福彭 :-(

        2
  •  0
  •   caf    16 年前

    在POSIX系统上,只要字符串不太长(不幸的是,“太长”取决于操作系统的特性,但至少是512字节),您就可以使用管道来执行此操作:

    #include <stdio.h>
    #include <unistd.h>
    #include <string.h>
    
    int string_to_foo(const char *str, size_t len)
    {
        int pipefd[2];
        FILE *infile;
    
        if (len > PIPE_BUF)
        {
            /* Error - string possibly too long */
            return -1;
        }
    
        if (pipe(pipefd))
        {
            /* Error - pipe() failed */
            return -1;
        }
    
        if (write(pipefd[1], str, len) < len)
        {
            close(pipefd[0]);
            close(pipefd[1]);
    
            /* Error - write() failed */
            return -1;
        }
    
        close(pipefd[1]);
    
        infile = fdopen(pipefd[0], "r");
    
        if (!infile)
        {
            close(pipefd[0]);
    
            /* Error - fdopen() failed */
            return -1;
        }
    
        foo(infile);
    
        fclose(infile);
    
        return 0;
    }