Open memstream ()

Da Gambas-it.org - Wikipedia.

La funzione open_memstream()

FILE *open_memstream (char **__bufloc, size_t *__sizeloc)

dichiarata nella libreria standard "/usr/include/stdio.h", crea un flusso I/O associato a un buffer di memoria allocato dinamicamente. Il buffer, cioè, si dimensiona automaticamente in base a quanto viene scritto nel flusso.

Questa funzione esterna consente di scrivere in un'area di memoria, puntata da una variabile di tipo Puntatore, come se si stesse scrivendo in un flusso del tipo FILE * previsto dal linguaggio C.


Volendola utilizzare in Gambas, bisognerà dichiararla con Extern, nonché bisognerà dichiarare la libreria di C, libc.so.6, nella quale la funzione è contenuta:

Private Extern open_memstream(__bufloc As Pointer, __sizeloc As Long) As Pointer In "libc:6"


Semplice esempio uso in Gambas in combinazione con le funzioni fwrite( ), fseek( ) e fclose( ):

Library "libc:6"

' FILE *open_memstream (char **__bufloc, size_t *__sizeloc)
' Open a stream that writes into a malloc'd buffer that is expanded as necessary.
Private Extern open_memstream(__bufloc As Pointer, __sizeloc As Pointer) As Pointer

' size_t fwrite (const void *__restrict __ptr, size_t __size, size_t __n, FILE *__restrict __s)
' Write chunks of generic data to STREAM.
Private Extern fwrite(__ptr As Pointer, __size As Long, __n As Long, __s As Pointer) As Long

' int fflush (FILE *__stream)
' Flush STREAM, or all streams if STREAM is NULL.
Private Extern fflush(__stream As Pointer) As Integer

' int fclose (FILE *__stream)
' Close STREAM.
Private Extern fclose(filestream As Pointer) As Integer


Public Sub Main()
 
 Dim dati As String
 Dim s, p As Pointer
 Dim lun As Long
   
   dati = "Testo qualsiasi"
   
' Apriamo in scrittura il Puntatore "s", che sarà gestito indirettamente mediante il Puntatore "p":
   p = open_memstream(VarPtr(s), VarPtr(lun))
   
' Scriviamo nel nuovo Puntatore "p" i valori contenuti nella variabile "dati":
   fwrite(VarPtr(dati), 1, Len(dati), p)
   
   fflush(p)
   
' La scrittura è avvenuta con il Puntatore ottenuto dalla funzione esterna "open_memstream( )",
' ma leggiamo sempre, dereferenziandolo, dal Puntatore "s":
   Print String@(s)
   
' Liberiamo la memoria precedentemente allocata:
   fclose(p)
  
End



Riferimenti