Sujet : Re: is STC a good supplementary library for C?
De : bc (at) *nospam* freeuk.com (Bart)
Groupes : comp.lang.cDate : 03. Aug 2024, 18:29:59
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v8llu7$3hdij$1@dont-email.me>
References : 1 2 3
User-Agent : Mozilla Thunderbird
On 03/08/2024 16:25, Stefan Ram wrote:
ram@zedat.fu-berlin.de (Stefan Ram) wrote or quoted:
Embracing these traits leads to more maintainable, efficient, and
understandable code. Instead of trying to force C to act like C++,
it's generally better to leverage C's strengths and use techniques
that are well-suited to the language's design and philosophy.
If you absolutely need a library, you (Mark) should totally check
out the Python library! It's been around forever, super reliable,
and constantly getting better. Here's a quick example program:
#include <Python.h>
int main() {
// Initialize the Python interpreter
Py_Initialize();
// Create a Python list
PyObject* pyList = PyList_New(0);
if (!pyList) {
fprintf(stderr, "Failed to create Python list\n");
Py_Finalize();
return 1;
}
// Add some integers to the list
for (int i = 0; i < 5; i++) {
PyObject* pyInt = PyLong_FromLong(i);
if (!pyInt) {
fprintf(stderr, "Failed to create Python integer\n");
Py_DECREF(pyList);
Py_Finalize();
return 1;
}
// PyList_Append increments the reference count of pyInt
if (PyList_Append(pyList, pyInt) < 0) {
fprintf(stderr, "Failed to append to list\n");
Py_DECREF(pyInt);
Py_DECREF(pyList);
Py_Finalize();
return 1;
}
// Decrease reference count of pyInt, as it's now stored in the list
Py_DECREF(pyInt);
}
// Print the list size
printf("List size: %zd\n", PyList_Size(pyList));
// Read and print the integers from the list
for (int i = 0; i < PyList_Size(pyList); i++) {
PyObject* item = PyList_GetItem(pyList, i); // Borrowed reference
if (PyLong_Check(item)) {
long value = PyLong_AsLong(item);
printf("List item %d: %ld\n", i, value);
} else {
fprintf(stderr, "List item %d is not an integer\n", i);
}
}
// Clean up
Py_DECREF(pyList);
Py_Finalize();
return 0;
}
, output:
List size: 5
List item 0: 0
List item 1: 1
List item 2: 2
List item 3: 3
List item 4: 4
.
This looks like it wouldn't run much faster than in Python. So why not just use Python? It would be a lot simpler!