C 代码中嵌入 Python 语句或使用 Python 模块 (Visual Studio 2013 环境设置)

本文详细介绍如何在C代码中嵌入Python语句和模块,包括环境配置、代码示例及常见应用场景,如利用Python模块增强C程序功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文链接:https://www.cnblogs.com/gaowengang/p/8529230.html

1) 新建一个 内嵌 Python 语句的 C 代码,

 

// This is a test for check insert the Python statements or module in C.

#include "Python.h"

int main(void)
{
    // execute python statements
    Py_Initialize();
    PyRun_SimpleString("import os");
    PyRun_SimpleString("print os.getcwd()");
    Py_Finalize();

    return 0;
}

 

2) Visual Studio 2013 环境设置

  右键单击工程,选择 Properties,

添加的 include 路径,

 复制重命名C盘 python27.lib 为 python27_d.lib

Linker 的 Input 添加上述 lib 的路径,

因为当前使用 64 位 Python,故修改编译平台为 x64,

continue,

之后编译即可。

3) C 中嵌入使用 Python 模块的语句,

  当前工程目录下建立一个 hello.py,

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def sayHi():
    print 'Hi, How are you?'

  C 文件为,

// This is a test for check insert the Python statements or module in C.

#include "Python.h"

int main(void)
{
    // execute python module
    Py_Initialize();
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('.')");
    PyObject * pModule = NULL;
    PyObject * pFunc = NULL;
    pModule = PyImport_ImportModule("hello");
    pFunc = PyObject_GetAttrString(pModule, "sayHi");
    PyEval_CallObject(pFunc, NULL);
    Py_Finalize();

    return 0;
}

   之后编译即可。

  一般情况下,用 C 扩展 Python 的情况居多,即把 C 代码包装成 Python 接口,在主 Python 程序中使用,可以提升程序运行效率或是为了利用已有的C代码。

  而将 Python 嵌入 C 一般是为了利用 Python 中现成的模块或方法,比较少用。

  更多内容请阅读 Python 官方 Help 文档。

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值