{"id":10021260,"date":"2026-02-19T12:38:59","date_gmt":"2026-02-19T04:38:59","guid":{"rendered":"https:\/\/itmax.cn\/?p=10021260"},"modified":"2026-02-19T12:38:59","modified_gmt":"2026-02-19T04:38:59","slug":"python-c-%e6%89%a9%e5%b1%95%ef%bc%9a%e7%94%a8-c-%e8%af%ad%e8%a8%80%e5%8a%a0%e9%80%9f%e6%a0%b8%e5%bf%83%e8%ae%a1%e7%ae%97","status":"publish","type":"post","link":"https:\/\/itmax.cn\/?p=10021260","title":{"rendered":"Python C \u6269\u5c55\uff1a\u7528 C \u8bed\u8a00\u52a0\u901f\u6838\u5fc3\u8ba1\u7b97"},"content":{"rendered":"<h2>Python C \u6269\u5c55\uff1a\u7528 C \u8bed\u8a00\u52a0\u901f\u6838\u5fc3\u8ba1\u7b97<\/h2>\n<p>Python C \u6269\u5c55\u5141\u8bb8\u5f00\u53d1\u8005\u7528 C \u8bed\u8a00\u7f16\u5199\u9ad8\u6027\u80fd\u7684 Python \u6a21\u5757\uff0c\u662f\u52a0\u901f\u6838\u5fc3\u8ba1\u7b97\u7684\u6709\u6548\u624b\u6bb5\u3002\u672c\u6587\u5c06\u6df1\u5165\u63a2\u8ba8 Python C \u6269\u5c55\u7684\u5f00\u53d1\u65b9\u6cd5\uff0c\u4ece\u57fa\u7840\u7684 API \u4f7f\u7528\u5230\u9ad8\u7ea7\u7684\u4f18\u5316\u6280\u5de7\uff0c\u5e2e\u52a9\u8bfb\u8005\u638c\u63e1\u7528 C \u8bed\u8a00\u52a0\u901f Python \u7a0b\u5e8f\u7684\u6838\u5fc3\u6280\u672f\u3002<\/p>\n<h3>Python C API \u57fa\u7840<\/h3>\n<p>Python C API \u63d0\u4f9b\u4e86\u4e30\u5bcc\u7684\u63a5\u53e3\uff0c\u7528\u4e8e\u5728 C \u4ee3\u7801\u4e2d\u64cd\u4f5c Python \u5bf9\u8c61\u548c\u8c03\u7528 Python \u51fd\u6570\u3002<\/p>\n<pre><code class=\"c\">#include &lt;Python.h&gt;\n\nstatic PyObject* hello_world(PyObject* self, PyObject* args) {\n    return Py_BuildValue(&quot;s&quot;, &quot;Hello from C!&quot;);\n}\n\nstatic PyMethodDef module_methods[] = {\n    {&quot;hello_world&quot;, hello_world, METH_NOARGS, &quot;Say hello from C&quot;},\n    {NULL, NULL, 0, NULL}\n};\n\nstatic struct PyModuleDef moduledef = {\n    PyModuleDef_HEAD_INIT,\n    &quot;hello_module&quot;,\n    &quot;A simple hello module&quot;,\n    -1,\n    module_methods\n};\n\nPyMODINIT_FUNC PyInit_hello_module(void) {\n    return PyModule_Create(&amp;moduledef);\n}<\/code><\/pre>\n<h3>Python \u8c03\u7528 C \u6269\u5c55<\/h3>\n<p>\u7f16\u5199\u597d C \u6269\u5c55\u540e\uff0c\u9700\u8981\u5728 Python \u4e2d\u7f16\u8bd1\u548c\u8c03\u7528\u5b83\u3002<\/p>\n<pre><code class=\"python\">import sys\nimport ctypes\n\ndef call_c_extension():\n    print(&quot;Python \u8c03\u7528 C \u6269\u6f14\u793a:&quot;)\n    \n    try:\n        import hello_module\n        result = hello_module.hello_world()\n        print(f&quot;\u7ed3\u679c: {result}&quot;)\n    except ImportError:\n        print(&quot;C \u6269\u5c55\u6a21\u5757\u672a\u627e\u5230&quot;)\n        print(&quot;\u9700\u8981\u5148\u7f16\u8bd1 C \u6269\u5c55&quot;)\n\ncall_c_extension()<\/code><\/pre>\n<h3>\u6570\u503c\u8ba1\u7b97\u4f18\u5316<\/h3>\n<p>\u4f7f\u7528 C \u8bed\u8a00\u8fdb\u884c\u6570\u503c\u8ba1\u7b97\u53ef\u4ee5\u663e\u8457\u63d0\u9ad8\u6027\u80fd\u3002<\/p>\n<pre><code class=\"c\">#include &lt;Python.h&gt;\n\nstatic PyObject* sum_squares(PyObject* self, PyObject* args) {\n    PyObject* list_obj;\n    if (!PyArg_ParseTuple(args, &quot;O&quot;, &amp;list_obj)) {\n        return NULL;\n    }\n    \n    if (!PyList_Check(list_obj)) {\n        PyErr_SetString(PyExc_TypeError, &quot;Expected a list&quot;);\n        return NULL;\n    }\n    \n    Py_ssize_t length = PyList_Size(list_obj);\n    long long sum = 0;\n    \n    for (Py_ssize_t i = 0; i &lt; length; i++) {\n        PyObject* item = PyList_GetItem(list_obj, i);\n        if (PyLong_Check(item)) {\n            long value = PyLong_AsLong(item);\n            sum += value * value;\n        }\n    }\n    \n    return PyLong_FromLongLong(sum);\n}\n\nstatic PyMethodDef math_methods[] = {\n    {&quot;sum_squares&quot;, sum_squares, METH_VARARGS, &quot;Calculate sum of squares&quot;},\n    {NULL, NULL, 0, NULL}\n};\n\nstatic struct PyModuleDef math_moduledef = {\n    PyModuleDef_HEAD_INIT,\n    &quot;math_extension&quot;,\n    &quot;High-performance math operations&quot;,\n    -1,\n    math_methods\n};\n\nPyMODINIT_FUNC PyInit_math_extension(void) {\n    return PyModule_Create(&amp;math_moduledef);\n}<\/code><\/pre>\n<h3>\u6027\u80fd\u5bf9\u6bd4<\/h3>\n<p>\u5bf9\u6bd4 Python \u539f\u751f\u5b9e\u73b0\u548c C \u6269\u5c55\u7684\u6027\u80fd\u5dee\u5f02\u3002<\/p>\n<pre><code class=\"python\">import time\n\ndef python_sum_squares(numbers):\n    return sum(x * x for x in numbers)\n\ndef performance_comparison():\n    print(&quot;\u6027\u80fd\u5bf9\u6bd4\u6d4b\u8bd5:&quot;)\n    \n    numbers = list(range(100000))\n    \n    start = time.time()\n    result1 = python_sum_squares(numbers)\n    time1 = time.time() - start\n    print(f&quot;Python \u5b9e\u73b0: {time1:.4f}\u79d2, \u7ed3\u679c: {result1}&quot;)\n    \n    try:\n        import math_extension\n        start = time.time()\n        result2 = math_extension.sum_squares(numbers)\n        time2 = time.time() - start\n        print(f&quot;C \u6269\u5c55\u5b9e\u73b0: {time2:.4f}\u79d2, \u7ed3\u679c: {result2}&quot;)\n        print(f&quot;\u6027\u80fd\u63d0\u5347: {time1\/time2:.1f}x&quot;)\n    except ImportError:\n        print(&quot;C \u6269\u5c55\u6a21\u5757\u672a\u627e\u5230&quot;)\n\nperformance_comparison()<\/code><\/pre>\n<h3>C \u6269\u5c55\u5f00\u53d1\u6d41\u7a0b<\/h3>\n<pre style=\"display:none;\"><code class=\"mermaid\">graph TD\n    A[\u9700\u6c42\u5206\u6790] --&gt; B[\u8bbe\u8ba1 C API]\n    B --&gt; C[\u7f16\u5199 C \u4ee3\u7801]\n    C --&gt; D[\u7f16\u5199 setup.py]\n    D --&gt; E[\u7f16\u8bd1\u6269\u5c55]\n    E --&gt; F[\u6d4b\u8bd5\u529f\u80fd]\n    F --&gt; G[\u6027\u80fd\u6d4b\u8bd5]\n    G --&gt; H{\u6027\u80fd\u8fbe\u6807?}\n    H --&gt;|\u5426| I[\u4f18\u5316 C \u4ee3\u7801]\n    I --&gt; C\n    H --&gt;|\u662f| J[\u53d1\u5e03\u4f7f\u7528]<\/code><\/pre>\n<h3>\u5185\u5b58\u7ba1\u7406<\/h3>\n<p>\u5728 C \u6269\u5c55\u4e2d\u6b63\u786e\u7ba1\u7406\u5185\u5b58\u662f\u907f\u514d\u5185\u5b58\u6cc4\u6f0f\u7684\u5173\u952e\u3002<\/p>\n<pre><code class=\"c\">#include &lt;Python.h&gt;\n\nstatic PyObject* create_large_array(PyObject* self, PyObject* args) {\n    int size;\n    if (!PyArg_ParseTuple(args, &quot;i&quot;, &amp;size)) {\n        return NULL;\n    }\n    \n    PyObject* result = PyList_New(size);\n    if (result == NULL) {\n        return NULL;\n    }\n    \n    for (int i = 0; i &lt; size; i++) {\n        PyObject* item = PyLong_FromLong(i * i);\n        if (item == NULL) {\n            Py_DECREF(result);\n            return NULL;\n        }\n        \n        PyList_SET_ITEM(result, i, item);\n    }\n    \n    return result;\n}\n\nstatic PyMethodDef memory_methods[] = {\n    {&quot;create_large_array&quot;, create_large_array, METH_VARARGS, &quot;Create large array&quot;},\n    {NULL, NULL, 0, NULL}\n};\n\nstatic struct PyModuleDef memory_moduledef = {\n    PyModuleDef_HEAD_INIT,\n    &quot;memory_extension&quot;,\n    &quot;Memory management examples&quot;,\n    -1,\n    memory_methods\n};\n\nPyMODINIT_FUNC PyInit_memory_extension(void) {\n    return PyModule_Create(&amp;memory_moduledef);\n}<\/code><\/pre>\n<h3>\u9519\u8bef\u5904\u7406<\/h3>\n<p>\u5728 C \u6269\u5c55\u4e2d\u6b63\u786e\u5904\u7406\u9519\u8bef\u5bf9\u4e8e\u6784\u5efa\u5065\u58ee\u7684\u6a21\u5757\u81f3\u5173\u91cd\u8981\u3002<\/p>\n<pre><code class=\"c\">#include &lt;Python.h&gt;\n\nstatic PyObject* safe_divide(PyObject* self, PyObject* args) {\n    double a, b;\n    if (!PyArg_ParseTuple(args, &quot;dd&quot;, &amp;a, &amp;b)) {\n        return NULL;\n    }\n    \n    if (b == 0.0) {\n        PyErr_SetString(PyExc_ZeroDivisionError, &quot;Division by zero&quot;);\n        return NULL;\n    }\n    \n    return PyFloat_FromDouble(a \/ b);\n}\n\nstatic PyObject* validate_input(PyObject* self, PyObject* args) {\n    PyObject* obj;\n    if (!PyArg_ParseTuple(args, &quot;O&quot;, &amp;obj)) {\n        return NULL;\n    }\n    \n    if (!PyLong_Check(obj)) {\n        PyErr_SetString(PyExc_TypeError, &quot;Expected an integer&quot;);\n        return NULL;\n    }\n    \n    long value = PyLong_AsLong(obj);\n    if (value &lt; 0) {\n        PyErr_SetString(PyExc_ValueError, &quot;Value must be non-negative&quot;);\n        return NULL;\n    }\n    \n    return PyLong_FromLong(value * value);\n}\n\nstatic PyMethodDef error_methods[] = {\n    {&quot;safe_divide&quot;, safe_divide, METH_VARARGS, &quot;Safe division&quot;},\n    {&quot;validate_input&quot;, validate_input, METH_VARARGS, &quot;Validate input&quot;},\n    {NULL, NULL, 0, NULL}\n};\n\nstatic struct PyModuleDef error_moduledef = {\n    PyModuleDef_HEAD_INIT,\n    &quot;error_extension&quot;,\n    &quot;Error handling examples&quot;,\n    -1,\n    error_methods\n};\n\nPyMODINIT_FUNC PyInit_error_extension(void) {\n    return PyModule_Create(&amp;error_moduledef);\n}<\/code><\/pre>\n<h3>NumPy \u96c6\u6210<\/h3>\n<p>C \u6269\u5c55\u53ef\u4ee5\u4e0e NumPy \u96c6\u6210\uff0c\u5b9e\u73b0\u9ad8\u6027\u80fd\u7684\u6570\u7ec4\u64cd\u4f5c\u3002<\/p>\n<pre><code class=\"python\">import numpy as np\nimport time\n\ndef numpy_integration_demo():\n    print(&quot;NumPy \u96c6\u6210\u6f14\u793a:&quot;)\n    \n    array = np.random.rand(1000000)\n    \n    start = time.time()\n    result = np.sum(array ** 2)\n    time1 = time.time() - start\n    print(f&quot;NumPy \u5b9e\u73b0: {time1:.4f}\u79d2&quot;)\n    \n    start = time.time()\n    result = sum(x ** 2 for x in array)\n    time2 = time.time() - start\n    print(f&quot;Python \u5b9e\u73b0: {time2:.4f}\u79d2&quot;)\n    \n    print(f&quot;\u6027\u80fd\u63d0\u5347: {time2\/time1:.1f}x&quot;)\n\nnumpy_integration_demo()<\/code><\/pre>\n<h3>\u591a\u7ebf\u7a0b\u652f\u6301<\/h3>\n<p>\u5728 C \u6269\u5c55\u4e2d\u652f\u6301\u591a\u7ebf\u7a0b\u9700\u8981\u6b63\u786e\u4f7f\u7528 GIL\u3002<\/p>\n<pre><code class=\"c\">#include &lt;Python.h&gt;\n#include &lt;pthread.h&gt;\n\nstruct thread_data {\n    long start;\n    long end;\n    long long* result;\n};\n\nvoid* thread_function(void* arg) {\n    struct thread_data* data = (struct thread_data*)arg;\n    long long sum = 0;\n    \n    for (long i = data-&gt;start; i &lt; data-&gt;end; i++) {\n        sum += i * i;\n    }\n    \n    data-&gt;result[0] = sum;\n    return NULL;\n}\n\nstatic PyObject* parallel_sum_squares(PyObject* self, PyObject* args) {\n    long n;\n    if (!PyArg_ParseTuple(args, &quot;l&quot;, &amp;n)) {\n        return NULL;\n    }\n    \n    int num_threads = 4;\n    pthread_t threads[num_threads];\n    struct thread_data thread_data[num_threads];\n    long long results[num_threads];\n    \n    long chunk_size = n \/ num_threads;\n    \n    for (int i = 0; i &lt; num_threads; i++) {\n        thread_data[i].start = i * chunk_size;\n        thread_data[i].end = (i == num_threads - 1) ? n : (i + 1) * chunk_size;\n        thread_data[i].result = &amp;results[i];\n        pthread_create(&amp;threads[i], NULL, thread_function, &amp;thread_data[i]);\n    }\n    \n    for (int i = 0; i &lt; num_threads; i++) {\n        pthread_join(threads[i], NULL);\n    }\n    \n    long long total_sum = 0;\n    for (int i = 0; i &lt; num_threads; i++) {\n        total_sum += results[i];\n    }\n    \n    return PyLong_FromLongLong(total_sum);\n}\n\nstatic PyMethodDef thread_methods[] = {\n    {&quot;parallel_sum_squares&quot;, parallel_sum_squares, METH_VARARGS, &quot;Parallel sum of squares&quot;},\n    {NULL, NULL, 0, NULL}\n};\n\nstatic struct PyModuleDef thread_moduledef = {\n    PyModuleDef_HEAD_INIT,\n    &quot;thread_extension&quot;,\n    &quot;Threaded operations&quot;,\n    -1,\n    thread_methods\n};\n\nPyMODINIT_FUNC PyInit_thread_extension(void) {\n    return PyModule_Create(&amp;thread_moduledef);\n}<\/code><\/pre>\n<h3>\u6027\u80fd\u4f18\u5316\u6280\u5de7<\/h3>\n<p>\u638c\u63e1 C \u6269\u5c55\u7684\u6027\u80fd\u4f18\u5316\u6280\u5de7\u53ef\u4ee5\u8fdb\u4e00\u6b65\u63d0\u5347\u6027\u80fd\u3002<\/p>\n<pre><code class=\"python\">import time\nfrom functools import lru_cache\n\ndef python_fibonacci(n):\n    if n &lt;= 1:\n        return n\n    return python_fibonacci(n - 1) + python_fibonacci(n - 2)\n\n@lru_cache(maxsize=None)\ndef cached_fibonacci(n):\n    if n &lt;= 1:\n        return n\n    return cached_fibonacci(n - 1) + cached_fibonacci(n - 2)\n\ndef optimization_demo():\n    print(&quot;\u4f18\u5316\u6280\u5de7\u6f14\u793a:&quot;)\n    \n    n = 35\n    \n    start = time.time()\n    result1 = python_fibonacci(n)\n    time1 = time.time() - start\n    print(f&quot;\u9012\u5f52\u5b9e\u73b0: {time1:.4f}\u79d2&quot;)\n    \n    start = time.time()\n    result2 = cached_fibonacci(n)\n    time2 = time.time() - start\n    print(f&quot;\u7f13\u5b58\u5b9e\u73b0: {time2:.4f}\u79d2&quot;)\n    \n    print(f&quot;\u6027\u80fd\u63d0\u5347: {time1\/time2:.1f}x&quot;)\n\noptimization_demo()<\/code><\/pre>\n<h3>\u8c03\u8bd5\u548c\u6d4b\u8bd5<\/h3>\n<p>\u6b63\u786e\u8c03\u8bd5\u548c\u6d4b\u8bd5 C \u6269\u5c55\u662f\u786e\u4fdd\u5176\u7a33\u5b9a\u6027\u7684\u91cd\u8981\u73af\u8282\u3002<\/p>\n<pre><code class=\"python\">import sys\nimport time\n\ndef test_c_extension():\n    print(&quot;C \u6269\u5c55\u6d4b\u8bd5:&quot;)\n    \n    try:\n        import math_extension\n        \n        test_cases = [\n            ([1, 2, 3], 14),\n            ([], 0),\n            ([0, 1, -1], 2)\n        ]\n        \n        for input_data, expected in test_cases:\n            result = math_extension.sum_squares(input_data)\n            assert result == expected, f&quot;\u6d4b\u8bd5\u5931\u8d25: {input_data} -&gt; {result} (\u671f\u671b {expected})&quot;\n            print(f&quot;\u6d4b\u8bd5\u901a\u8fc7: {input_data} -&gt; {result}&quot;)\n        \n        print(&quot;\u6240\u6709\u6d4b\u8bd5\u901a\u8fc7&quot;)\n        \n    except ImportError:\n        print(&quot;C \u6269\u5c55\u6a21\u5757\u672a\u627e\u5230&quot;)\n    except AssertionError as e:\n        print(f&quot;\u6d4b\u8bd5\u5931\u8d25: {e}&quot;)\n\ntest_c_extension()<\/code><\/pre>\n<h3>\u603b\u7ed3<\/h3>\n<p>Python C \u6269\u5c55\u662f\u52a0\u901f\u6838\u5fc3\u8ba1\u7b97\u7684\u6709\u6548\u624b\u6bb5\uff0c\u901a\u8fc7\u7528 C \u8bed\u8a00\u91cd\u5199\u5173\u952e\u4ee3\u7801\u6bb5\uff0c\u53ef\u4ee5\u83b7\u5f97\u663e\u8457\u7684\u6027\u80fd\u63d0\u5347\u3002\u638c\u63e1 Python C API\u3001\u5185\u5b58\u7ba1\u7406\u3001\u9519\u8bef\u5904\u7406\u7b49\u6838\u5fc3\u6280\u672f\uff0c\u4ee5\u53ca\u591a\u7ebf\u7a0b\u652f\u6301\u3001\u6027\u80fd\u4f18\u5316\u7b49\u9ad8\u7ea7\u6280\u5de7\uff0c\u53ef\u4ee5\u6784\u5efa\u51fa\u9ad8\u6027\u80fd\u7684 Python \u6269\u5c55\u6a21\u5757\u3002<\/p>\n<p>\u5728\u5b9e\u9645\u5f00\u53d1\u4e2d\uff0c\u9700\u8981\u5e73\u8861\u5f00\u53d1\u6210\u672c\u548c\u6027\u80fd\u6536\u76ca\uff0c\u9009\u62e9\u5408\u9002\u7684\u4f18\u5316\u7b56\u7565\u3002C \u6269\u5c55\u867d\u7136\u5f00\u53d1\u590d\u6742\u5ea6\u8f83\u9ad8\uff0c\u4f46\u5bf9\u4e8e\u6027\u80fd\u8981\u6c42\u6781\u9ad8\u7684\u573a\u666f\uff0c\u4ecd\u7136\u662f\u4e0d\u53ef\u66ff\u4ee3\u7684\u89e3\u51b3\u65b9\u6848\u3002<\/p>\n<p><a href=\"https:\/\/segmentfault.com\/a\/1190000047614275\">https:\/\/segmentfault.com\/a\/1190000047614275<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python C \u6269\u5c55\uff1a\u7528 C \u8bed\u8a00\u52a0\u901f\u6838\u5fc3\u8ba1\u7b97 Python C \u6269\u5c55\u5141\u8bb8\u5f00\u53d1\u8005\u7528 C \u8bed\u8a00\u7f16\u5199\u9ad8\u6027\u80fd\u7684 P [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[4],"tags":[],"class_list":["post-10021260","post","type-post","status-publish","format-standard","hentry","category-share"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts\/10021260","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10021260"}],"version-history":[{"count":0,"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts\/10021260\/revisions"}],"wp:attachment":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10021260"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10021260"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10021260"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}