1

I use PyImport_ImportModule to import python module in C++.

Now i have two Python module files with same name in different folder like:

c:\Demo1\plugin.py and c:\Demo2\plugin.py

I know in python, can use

import Demo1.plugin as p1
import Demo2.plugin as p2

How to do it in C++, with PyImport_ImportModule or otherwise?

I find a workaround: execute python c:\Demo1\plugin.py and get the output from it, but it isn't a good solution.

2
  • 1
    What do you mean by 'import'? Do you mean #include? Commented Jun 20, 2019 at 15:16
  • No, i mean c++ use api PyImport_ImportModule to import python module files and call their functions Commented Jun 20, 2019 at 15:18

2 Answers 2

2

To just import a file I would use PyObject* PyImport_ImportModule(const char *name)

PyObject *p1 = PyImport_ImportModule( "Demo1.plugin" );
PyObject *p2 = PyImport_ImportModule( "Demo2.plugin" );

which should work just fine if your path is set correctly. Alternatively you can use PyObject* PyImport_Import(PyObject *name), but then you have to manage the refcounting of the name.

PyObject *s1 = PyUnicode_FromString( "Demo1.plugin" );
PyObject *s2 = PyUnicode_FromString( "Demo2.plugin" );

PyObject *p1 = PyImport_Import( s1 );
PyObject *p2 = PyImport_Import( s2 );

Py_DECREF( s1 );
Py_DECREF( s2 );

You may need to add an __init__.py file to the Demo1 and Demo2 folders.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you , it solves my problem, i use PyImport_ImportModule( "Demo1.plugin" ); before, but my path set error ,so it failed. Now i set right sys.path and the two solutions is all effective to me
0

You can include them in this manner

include "headers/myHeader.h"
include "../moreHeaders/myHeader.h"

Just make sure to use different namespaces in both of the header files to access the variables and functions

1 Comment

Sorry, i changed the question's title, i mean call python module in c++ , please read my question again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.