파이썬 c API 하다 만거

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "Python.h"
 
static PyObject *ErrorObject;
 
 static PyObject* sample_dictest(PyObject *self, PyObject *args)
{
    PyObject* dic;
    int len;
 
    if (!PyArg_ParseTuple(args, "O", &dic)) /* 파이썬 객체를 dic로 전달 받는다 */
        return NULL;
    if (!PyDict_Check(dic)) { /* 사전인지 검사 */
        /* 사전이 아니면 예외 발생. 일단 건너뛰자 */
        PyErr_SetString(ErrorObject, "my exception");
        return NULL;
    }
    len = PyDict_Size(dic);     /* 사전의 길이를 얻는다 */
    printf("Yes, this is dictionary of len %d\n", len); /* 메시지 출력 */
    Py_INCREF(Py_None); /* 파이썬 None 객체 리턴 */
    return Py_None;
}
 
 
static PyObject* sample_system(PyObject *self, PyObject *args)
{
    char *command;
    int sts;
    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    return Py_BuildValue("i", sts);
}
 
 static PyObject* my_sort(PyObject *self, PyObject *args)
{
    PyObject* list;
    int len;
 
    if (!PyArg_ParseTuple(args, "O", &list)) /* 파이썬 객체를 dic로 전달 받는다 */
        return NULL;
    if (!PyList_Check(list)) { /* 사전인지 검사 */
        /* 사전이 아니면 예외 발생. 일단 건너뛰자 */
        PyErr_SetString(ErrorObject, "my exception");
        return NULL;
    }
    len = PyList_Size(list);     /* 사전의 길이를 얻는다 */
    printf("Yes, this is List of len %d\n", len); /* 메시지 출력 */
    Py_INCREF(Py_None); /* 파이썬 None 객체 리턴 */
    return Py_None;
}
 
 
 
static struct PyMethodDef my_methods[] = {
 {"system",       sample_system,    METH_VARARGS}, /* name, address */
 {"dictest",      sample_dictest,   METH_VARARGS},
 {"sort",         my_sort,          METH_VARARGS},
 {NULL,         NULL}                              /* end, for initmodule */
};
 
void initsample()
{
    PyObject *m;
    /* 모듈을 생성하고 함수를 등록한다 */
    m = Py_InitModule("mylib", my_methods);        /* registration hook */
    /* 기타의 초기화 처리 */
    ErrorObject = Py_BuildValue("s", "sample error");
    /* ... */
}

'Sorce Bank' 카테고리의 다른 글

Python HW 1번문제  (0) 2010.05.06
그래픽스 실습 4.27  (0) 2010.04.27
네트워크 홈워크 1  (0) 2010.03.25
GeneralTree to BinaryTree  (2) 2010.03.18
Java Binary Tree  (0) 2010.03.14