[Tutor] RE Embedding Python in C

Alan Gauld alan.gauld at yahoo.co.uk
Tue Jul 9 15:10:00 EDT 2019


On 09/07/2019 15:13, Ibarra, Jesse wrote:

Caveat: I'm no expert on embedding and indeed have only done
it once using the examples in the docs. However, based on
my general Python experience...

> I then embedded the example using C/Python API:
> https://docs.python.org/3.6/extending/embedding.html#pure-embedding
> 
> int main(){
>   PyObject *pModule, *pName;
> 
>   Py_Initialize();
>   PyRun_SimpleString("import sys");
>   PyRun_SimpleString("sys.path.append('.')");
> 
>   pModule = PyImport_ImportModule("Rosenbrock_Function");
>   pName = PyImport_ImportModule("Rosenbrock_Function");

These import the same module twice. But Python usually checks if a
module is already imported so I'm guessing it does the same here.

>   Py_XDECREF(pModule);
>   Py_XDECREF(pName);

Maybe if you decrement the count after each import you will
get the result you want?

Although I'm guessing that relying on code to run via an import
is probably a bad practice. You'd normally expect to import
the module then call a function.

But that's mostly guesswork, so I could well be wrong!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list