I'm trying to extend Python 3 with C++ in MSVC++ 2010. I'm completely new to this kind of thing, and I'm also not very proficient in C++ yet. Following from the python documentation and help I received here earlier, I've written the following code which compiles and runs successfully:
#include <Python.h>
#include <iostream>
using namespace std;
static PyObject *SpamError;
static PyObject *spam_system(PyObject *self, PyObject *args)
{
const char *command;
int sts;
if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
sts = system(command);
return PyLong_FromLong(sts);
}
static PyMethodDef SpamMethods[] = {
{"system", spam_system, METH_VARARGS,
"Execute a shell command."},
{NULL, NULL, 0, NULL} /* Sentinel */
};
static struct PyModuleDef spammodule = {
PyModuleDef_HEAD_INIT,
"spam", /* name of module */
NULL, /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
SpamMethods
};
PyMODINIT_FUNC
PyInit_spam(void)
{
PyObject *m;
m = PyModule_Create(&spammodule);
if (m == NULL)
return NULL;
SpamError = PyErr_NewException("spam.error", NULL, NULL);
Py_INCREF(SpamError);
PyModule_AddObject(m, "error", SpamError);
return m;
}
int main(int argc, wchar_t *argv[])
{
// Add a builtin module, before Py_Initialize
PyImport_AppendInittab("spam", PyInit_spam);
// Pass argv[0] to the Python Interpreter
Py_SetProgramName(argv[0]);
// Initialise the Python interpreter
Py_Initialize();
// Import module
PyImport_ImportModule("spam");
cout << "test" << endl;
system("PAUSE");
}
I'm still unsure about a few things though; do I need to create a header file for this, and how should I go about doing that?
Also, how am I ultimately meant to make it so that I call the extension through the python shell or within a program?