4

I am trying to write a simple C/C++ program in Ubuntu 17.10 to call python function using embedding. However, it always complained that it is unable to import the module using PyImport_ImportModule.

I have included Python.h in the cpp file and compile it like this:

g++ -L/usr/lib/python3.6/config-3.6m-x86_64-linux-gnu/ -g -o main main.cpp -I/usr/include/python3.6 -lpython3.6

I have tried the following things but none of the approach works:

  1. add the current path to path using PySys_GetObject and PyList_Insert (as per this link)
  2. set PYTHONPATH=/tmp then run the main program (as per this link)

/tmp/main.cpp

#include <iostream>
#include <python3.6/Python.h>
using namespace std;

int main()
{
    Py_Initialize();
    PyObject* sysPath = PySys_GetObject("path");
    PyObject *path = PyBytes_FromString("/tmp");
    int result = PyList_Append(sysPath, path);

    PyObject* module = PyImport_ImportModule("hello");

    if (0 != module)
    {
        PyObject* helloFunc = PyObject_GetAttrString(module, "hello");
        if (helloFunc)
        {
            PyEval_CallObject(helloFunc, 0);
        }
        else
        {
            fprintf(stderr, "hello function is NULL");
        }
    }
    else
    {
        fprintf(stderr, "hello module is NULL -- somehow");
    }

    Py_Finalize();
    return 0;
}

/tmp/hello.py

class hello(object):
    def __init__(self):
        print("Hello world: init")

    def hello(self):
        print("Hello world: hello")

Please can someone tell me why PyImport_ImportModule always return NULL in my simple program?

Many thanks!

HeiHei
  • 346
  • 1
  • 2
  • 10

0 Answers0