blob: ad1acf35456bb11b6af017a9cb6166effc7f6a49 (
plain)
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
|
#include <Python.h>
#include <stdlib.h>
#include "stringlist.h"
struct StringList
{
char **list;
unsigned int count;
};
// Creates a String list to use with the library.
// len is the number of strings in the list.
StringList* stringListCreate(size_t len)
{
StringList *ret = malloc(sizeof(StringList));
ret->count = len;
ret->list = malloc(sizeof(char*) * len);
return ret;
}
/*
* Inserts the string str in the list l at position pos.
* Return True if it succeeded, False if not.
*/
int stringListInsertAt(StringList *l, unsigned int pos, char *str)
{
if(!l || !l->list || l->count < pos)
return 0;
l->list[pos] = str;
return 1;
}
/*
* Returns the number of strings in the list
*/
unsigned int stringListCount(StringList *l)
{
if (!l)
return 0;
return l->count;
}
/*
* Returns the String at position pos
*/
char* stringListGetAt(StringList *l, unsigned int pos)
{
if (!l || !l->list || pos >= l->count)
return NULL;
return l->list[pos];
}
/*
* Converts a Python list object to a C String list
*/
StringList* listToCList(PyObject* list)
{
if (!list || !PyList_Check(list))
return NULL;
unsigned int len = PyList_Size(list);
StringList *ret = malloc(sizeof(StringList));
ret->count = len;
ret->list = malloc(sizeof(char*) * len);
for (unsigned int i = 0; i < len; i++)
{
//Item are copied so that the PyObject can be deleted after the call without
//destroying the data in the returned list.
PyObject *elem = PyList_GetItem(list, i);
char *val = NULL;
if (PyUnicode_Check(elem))
{
PyObject *tmp = PyUnicode_AsUTF8String(elem);
val = strdup(PyString_AsString(tmp));
Py_DECREF(tmp);
}
else if (PyString_Check(elem))
{
val = PyString_AsString(elem);
}
ret->list[i] = strdup(val);
}
return ret;
}
/*
* Converts a C String list to a Python List object
*/
PyObject* cListToPyList(StringList* list)
{
if (!list)
Py_RETURN_NONE;
PyObject *ret = PyList_New(list->count);
for(unsigned int i = 0; i < list->count; i++)
{
PyList_SetItem(ret, i, PyBytes_FromString(list->list[i]));
}
return ret;
}
/*
* Prints a C String list.
*/
void stringListPrint(StringList* list)
{
if (!list)
return;
for(unsigned int i = 0; i < list->count; i++)
{
printf("\"%s\"", list->list[i]);
// No coma after the last item.
if (i < list->count - 1)
printf(", ");
}
}
/*
* Frees a string list and it's data
*/
void stringListFree(StringList* list)
{
if (list && list->list)
{
for(unsigned int i = 0; i < list->count; i++)
{
free(list->list[i]);
}
free(list->list);
}
if (list)
free(list);
}
|