Pass InputStream through JNA to C code as a File Pointer

▼魔方 西西 提交于 2019-12-05 15:01:45

I don't believe you can do this - you have no easy way to access the internals of of an InputStream instance, and even a FileInputStream will most likely not be implemented on top of a stdio FILE *. To see what your Java interface should be like, you'll need to post more about the foo function - what it does and how you use it.

If you don't care about what the FILE * actually does, you can code up using JNA to call fopen, passing in the file name and open mode, and pass the result as an opaque value through to foo, e.g. (pseudocode):

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

Update: If you need to have a string which contains data which you need treated as if it were in a file, I think you are out of luck. Unfortunately, the standard C library is not built on top of a stream abstraction, which means that you are unlikely to be able to achieve what you want unless you can open what looks like a filename but leads to your string data; however, it's going to be much, much easier to bite the bullet and save the string to a temporary file, then open that with fopen :-(

On POSIX systems, you can do this using a pipe, as long as the string isn't too long (unfortunately "too long" depends on the characteristics of the operating system, but is at least 512 bytes):

#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;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!