Re: Loading database from string (C API)

Jan Wielemaker <[email protected]>
Newsgroups gmane.comp.ai.prolog.swi
Message-ID <[email protected]>
Hu Edd,

On 12/06/2013 02:40 PM, Edd Barrett wrote:
> Hi,
>
> I am writing a VM which embeds SWI-prolog using the C interface (I am
> actually calling the SWI C interface via Python-CFFI, but it is all the
> same).
>
> I need to be able to parse Prolog source code (in a C string) into the Prolog
> database. Looking at the FFI documentation [1] I don't see an obvious way to do
> this. I guess one way is to write the Prolog source code to a file and
> construct a query to consult/1.

That will surely work :-)

> Maybe it is possible to write the code to a memory file and use load_file/2
> to load from a stream, but that seems convoluted too.

You can do

	load_files(mydata, [stream(Stream)]).

That will compile the file from Stream and claim it was loaded from a
file named `mydata'.

So, the question becomes how to get a Prolog stream from a C string.
You can do that using the stream API defined in SWI-Stream.h but still
undocumented.  What you want is something like below.  The default
encoding is ISO Latin 1.  See SWI-Stream.h for other values.

int
open_stream(char *s, term_t t)
{ IOSTREAM *stream;

   stream = Sopen_string(NULL, s, strlen(s), "r");
   stream->encoding = ENC_UTF8;

   return PL_unify_stream(t, stream);
}

	Enjoy --- Jan
	
> P.S. Typo in documentation:
> "security riscs" -> "security risks"
> http://www.swi-prolog.org/pldoc/man?section=memory-files

Thanks.  Fixed (will be on the site next release).

>
> [1] http://www.swi-prolog.org/pldoc/man?section=foreign
>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.