I was just playing with python c api for the first time and I've written this (test) module for python:
Code:
#include <Python.h>
#define VAL1 1
#define VAL2 2
struct name_val {
char* name;
int val;
};
struct name_val name_value[]= {
{ "str1", VAL1 },
{ "str2", VAL2 },
{ NULL, -1 }
};
static PyObject *dic;
static PyObject *test_smthg(PyObject *self, PyObject *args)
{
int n;
printf("This is just a test.\n");
if (!PyArg_ParseTuple(args,"i:fact",&n))
return NULL;
return Py_BuildValue("i", n);
}
static PyObject *test_createdic(void)
{
int i;
if (!(dic = PyDict_New()))
return NULL;
for (i = 0; name_value[i].name != NULL; i++) {
if (PyDict_SetItemString(dic, name_value[i].name,
PyInt_FromLong(name_value[i].val)) < 0)
return NULL;
}
Py_RETURN_NONE;
}
static PyMethodDef TestMethods[] = {
{"smthg", test_smthg, METH_VARARGS,
"Just a test for python c api."},
{"createdic", test_createdic, METH_NOARGS,
"function to create a dictionary"},
{NULL, NULL, 0, NULL} /* Sentinel */
};
PyMODINIT_FUNC inittest(void)
{
(void) Py_InitModule("test", TestMethods);
}
When i try to call one of the methods ( this after i had imported this module in python) it gives me this error:
AttributeError: 'module' object has no attribute 'smthg'
I need some help to figure out why it gives me this error and also i want to ask if this is the right way to create a dictionary.