To be able to use the python engine from a C or C++ application,
you need to make sure that Py_Initialize()
is called at the beginning
of your main()
function, and that Py_Finalize()
is called at the
end. What you also don't see is that the import_module()
function
actually produces an error, but it does this using the python error
mechanism. You can make this visible by adding the following code
below import_module()
:
if (PyErr_Occurred())
{
PyErr_Print();
return -1;
}
If you do that, you'll see the following error appear:
ImportError: No module named module
To be able to use a Cython module, you have to make sure
that that module's init function is called, in this case
initmodule()
. Unfortunatly it seems that the declaration of
this function is not present in the generated header file,
so we'll have to manually add it above the main:
PyMODINIT_FUNC initmodule(void);
Together with placing the vector
include line first and a small
fix in the cout
line, the code then becomes:
#include <vector>
#include <iostream>
#include "module_api.h"
using namespace std;
PyMODINIT_FUNC initmodule(void);
int main() {
Py_Initialize();
initmodule();
import_module();
if (PyErr_Occurred())
{
PyErr_Print();
return -1;
}
vector<int> *v = func();
cout << "v[0] = " << (*v)[0] << endl;
Py_Finalize();
return 0;
}
Which, at least on my system, produces the output:
v[0] = 3