Windows下C语言如何调用Python脚本?

99ANYc3cd6
预计阅读时长 20 分钟
位置: 首页 C语言 正文
  1. 通过系统命令调用(最简单)

    windows c语言调用python
    (图片来源网络,侵删)
    • 将 Python 脚本当作一个独立的程序来执行。
    • C 程序创建一个子进程来运行 python.exe
    • 优点:实现简单,不依赖 Python 的 C API。
    • 缺点:性能开销大(启动新进程),交互复杂(通过命令行参数和标准输入/输出),无法直接获取 Python 对象。
  2. 嵌入 Python 解释器(最强大、最常用)

    • 将 Python 解释器直接链接到你的 C 程序中。
    • C 程序可以启动、停止、与 Python 解释器进行深度交互。
    • 优点:性能高,交互能力强,可以直接在 C 和 Python 之间传递数据。
    • 缺点:配置复杂,需要链接 Python 的库文件和头文件,代码量稍多。

下面我将详细介绍这两种方式,并提供完整的代码示例和配置步骤。


准备工作:安装 Python 和获取路径

无论使用哪种方式,你都需要一个 Python 环境。

  1. 安装 Python:从 Python 官网 下载并安装 Python。强烈建议勾选 "Add Python to PATH" 选项。
  2. 找到 Python 路径
    • 打开命令提示符(CMD)或 PowerShell。
    • 输入 where pythonwhere python3,它会显示 Python 可执行文件所在的路径。C:\Users\YourUser\AppData\Local\Programs\Python\Python311\python.exe
    • 记录下这个路径,特别是 Python311 这个目录,里面包含了 include(头文件)和 libs(库文件)文件夹,这是方式二的关键。

通过系统命令调用

这是最直接的方法,C 程序通过 system() 函数或 CreateProcess() Windows API 来执行一个命令行指令。

windows c语言调用python
(图片来源网络,侵删)

示例场景

我们有一个简单的 Python 脚本 add.py,它接收两个命令行参数,计算它们的和并打印。

add.py

import sys
if len(sys.argv) != 3:
    print("Usage: python add.py <num1> <num2>")
    sys.exit(1)
try:
    num1 = int(sys.argv[1])
    num2 = int(sys.argv[2])
    result = num1 + num2
    print(f"The sum of {num1} and {num2} is: {result}")
except ValueError:
    print("Error: Please provide valid integers.")
    sys.exit(1)

C 程序 call_python_cmd.c 这个程序会使用 system() 函数来调用上面的 Python 脚本。

#include <stdio.h>
#include <stdlib.h> // 用于 system()
int main() {
    printf("C Program: Calling Python script via command line...\n");
    // 定义要传递给Python脚本的参数
    int arg1 = 50;
    int arg2 = 25;
    // 构建命令字符串
    // 注意:这里假设 python.exe 在系统 PATH 中
    char command[256];
    sprintf(command, "python add.py %d %d", arg1, arg2);
    printf("Executing command: %s\n", command);
    // 执行命令
    int status = system(command);
    if (status == 0) {
        printf("Python script executed successfully.\n");
    } else {
        printf("Failed to execute Python script. Return code: %d\n", status);
    }
    return 0;
}

编译和运行

  1. add.pycall_python_cmd.c 放在同一个文件夹下。
  2. 打开 Visual Studio 的 Developer Command Prompt for VS(或者 MinGW 的终端)。这个环境会自动配置好编译器路径
  3. 编译 C 程序:
    gcc call_python_cmd.c -o call_python_cmd.exe
  4. 运行:
    .\call_python_cmd.exe

预期输出:

windows c语言调用python
(图片来源网络,侵删)
C Program: Calling Python script via command line...
Executing command: python add.py 50 25
The sum of 50 and 25 is: 75
Python script executed successfully.

嵌入 Python 解释器(C API)

这种方式更强大,但配置也更复杂,你需要告诉 C 编译器去哪里找 Python 的头文件(.h)和库文件(.lib)。

示例场景

C 程序直接调用 Python 脚本中的一个函数,并获取返回值,我们使用上面的 add.py 脚本,并稍作修改,让它定义一个函数。

add.py (修改版)

# 定义一个可以被C调用的函数
def add_numbers(a, b):
    """计算两个整数的和"""
    print(f"Python: Received {a} and {b}")
    result = a + b
    print(f"Python: Returning {result}")
    return result

C 程序 embed_python.c 这个程序将包含所有必要的步骤来初始化 Python、导入模块、调用函数并处理返回值。

#include <Python.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
    // 1. 初始化Python解释器
    Py_Initialize();
    if (!Py_IsInitialized()) {
        fprintf(stderr, "Error: Failed to initialize Python interpreter.\n");
        return 1;
    }
    // 2. 将当前目录添加到Python的模块搜索路径中
    // 这样Python才能找到add.py文件
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('.')");
    // 3. 导入Python模块 (add.py -> add module)
    PyObject* pName = PyUnicode_DecodeFSDefault("add");
    if (!pName) {
        PyErr_Print();
        fprintf(stderr, "Error: Failed to create Python string for module name.\n");
        Py_Finalize();
        return 1;
    }
    PyObject* pModule = PyImport_Import(pName);
    Py_DECREF(pName);
    if (!pModule) {
        PyErr_Print();
        fprintf(stderr, "Error: Failed to import module 'add'.\n");
        Py_Finalize();
        return 1;
    }
    // 4. 获取模块中的函数对象 (add_numbers)
    PyObject* pFunc = PyObject_GetAttrString(pModule, "add_numbers");
    if (!pFunc || !PyCallable_Check(pFunc)) {
        if (PyErr_Occurred()) PyErr_Print();
        fprintf(stderr, "Error: Cannot find function 'add_numbers' or it's not callable.\n");
        Py_DECREF(pModule);
        Py_Finalize();
        return 1;
    }
    // 5. 准备C函数的参数 (Python元组)
    // PyObject *Py_BuildValue(char *format, ...)
    // "ii" 表示两个整数参数
    PyObject* pArgs = Py_BuildValue("(ii)", 100, 200);
    // 6. 调用Python函数
    // NULL表示没有关键字参数
    PyObject* pResult = PyObject_CallObject(pFunc, pArgs);
    Py_DECREF(pArgs); // 参数元组不再需要
    if (pResult != NULL) {
        // 7. 处理Python函数的返回值
        // 将Python的整数对象转换为C的long
        long result = PyLong_AsLong(pResult);
        printf("C: Received result from Python: %ld\n", result);
        Py_DECREF(pResult);
    } else {
        PyErr_Print();
        fprintf(stderr, "Error: Function call failed.\n");
    }
    // 8. 清理
    Py_DECREF(pFunc);
    Py_DECREF(pModule);
    Py_Finalize();
    return 0;
}

编译和运行(关键步骤)

你需要使用 /link 选项来链接 Python 的库文件。

  1. 打开 Developer Command Prompt for VS

  2. 获取你的 Python 版本信息,在终端输入 python -VPython 3.11.4,你需要 python311.lib 这样的库文件。

  3. 编译命令

    • /I:指定 Python 头文件(include)的路径。
    • /link:链接外部库。
    • /LIBPATH:指定 Python 库文件(libs)的路径。
    • python311.lib:要链接的库文件名(根据你的版本可能不同,如 python39.lib)。

    **将

-- 展开阅读全文 --
头像
{dede:field.typeurl/} 是什么标签?
« 上一篇 2025-11-28
dede cms 版权信息怎么改?
下一篇 » 2025-11-28

相关文章

取消
微信二维码
支付宝二维码

目录[+]