Here's a canonical example of an extension program for embedded Python 3.x in C / C ++:
#include <Python.h>
static PyObject* emb_foo(PyObject *self, PyObject *args)
{
char const* n = "I am foo";
return Py_BuildValue("s", n);
}
static PyMethodDef EmbMethods[] = {
{"foo", emb_foo, METH_VARARGS, "Returns foo"},
{NULL, NULL, 0, NULL}
};
static PyModuleDef EmbModule = {
PyModuleDef_HEAD_INIT, "emb", NULL, -1, EmbMethods,
NULL, NULL, NULL, NULL
};
static PyObject* PyInit_emb(void)
{
return PyModule_Create(&EmbModule);
}
int main()
{
PyImport_AppendInittab("emb", &PyInit_emb);
Py_Initialize();
PyRun_SimpleString("import emb\n");
PyRun_SimpleString("print(emb.foo())\n");
Py_Finalize();
return 0;
}
I am adding a module embto the built-in built-in interpreters. I would also like to import it automatically, so users do not need to set an operator import embin their scripts supplied with my built-in interpreter. I am trying to use two import methods in lines (1) and (2) .
(1), emb (3). , (1) (2) API C API Python 3, (3 ) :
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'emb' is not defined
, .
/ ?
Python 3 :
, , , PyImport_ImportModule --, PyImport_ImportModuleEx ( ?) , "" .