0

I have the following function (from the lionet asn1 compiler API):

int xer_fprint(FILE *stream, struct asn_TYPE_descriptor_s *td, void *sptr);

The first paramter is a FILE*, and that is where the output goes.

This works:

xer_fprint(stdout, &asn_struct, obj);

and so does this:

FILE* f = fopen("test.xml", "w");
xer_fprint(f, &asn_struct, obj);
fclose(f);

But I need this data in a string (std::string preferably).

How do I do that?

Nitay
  • 4,193
  • 6
  • 33
  • 42

4 Answers4

1

On Linux you have fmemopen which creates a FILE * handle to a temporary in-memory buffer:

char * buffer = malloc(buf_size);
FILE * bufp = fmemopen(buffer, buf_size, "wb");

If this is unavailable then you can try to attach a FILE * to a POSIX shared memory file descriptor:

int fd = shm_open("my_temp_name", O_RDWR | O_CREAT | O_EXCL, 0);
// unlink it
shm_unlink("my_temp_name");
// on Linux this is equivalent to
fd = open("/dev/shm/my_temp_name", O_RDWR | O_CREAT | O_EXCL); unlink("/dev/shm/my_temp_name");

FILE * shmp = fdopen(fd, "wb");

// use it

char * buffer = mmap(NULL, size_of_buf , PROT_READ, MAP_SHARED, fd, 0);
Sergey L.
  • 21,822
  • 5
  • 49
  • 75
0

In C: open the file and read it back. Use a suitable temporary file location. There is no standard way to create an in-memory ("string stream") version of a FILE *.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

GNU's libc provides string streams as an extension to the standard library.

The fmemopen and open_memstream functions allow you to do I/O to a string or memory buffer. These facilities are declared in stdio.h.

diapir
  • 2,872
  • 1
  • 19
  • 26
0

As I understand the question, you want to call xer_fprint to write to an in-memory buffer. I don't think there is a direct way to do this, but I think you could use a pipe. The following should give you some ideas of what to try:

int rw[2]; 
int ret = pipe(rw);
FILE* wrFile = fdopen(rd[1], 'w'); 
xer_fprint(wrFile, &asn_struct, obj); 

// ...  later/in another thread 
namespace io = boost::iostreams; 
io::stream_buffer<io::file_descriptor_source> fpstream (rw[0]);
std::istream in (&fpstream);
std::string data; 
in >> data; 
JoeD
  • 171
  • 6