在Windows命令行下使用Python解释器编译C++代码

0 投票
1 回答
1528 浏览
提问于 2025-04-18 12:36

我的环境是:

Windows 7。

使用 PyDev IDE(在 eclipse 中)。

Python 2.7。

我想编译和测试一些我写的 C++ 代码(将来,这些代码会由一个 Python 脚本生成)。我需要编译一个简单的 .c 文件,以便用作 Python 扩展。

现在我的代码是:

/*
file: test.c 
This is a test file for add operations.
 */
float my_add(float a, float b)
{
    float res;
    res = a + b;
    return res;
}

还有这个 .py 文件:

import subprocess as sp
import os
class PyCompiler():
    def __init__(self, name):
        self.file = name
        self.init_command = r"C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\vcvars32.bat"
        self.compiler_command = r"C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\cl.exe"
        sp.call(self.init_command + " " + self.file)

    def compile(self):
        alfa = sp.call(self.compiler_command)
        print(alfa)

TestCode = PyCompiler(r"C:\Python27\CodeGenerator\src\nested\test.c")
TestCode.compile()

如果我运行这个脚本,我得到:

output

这意味着我在 PyCompiler.compile 方法中遇到了错误,因为 subprocess.call 的返回值不是 1。

你能给我一些关于这个问题的指导吗?

你知道还有其他方法可以做到这一点吗?

1 个回答

0

我其实通过安装MinGW解决了这个问题,然后用它来编译我的C代码。我的Python代码如下:

import subprocess as sp
import os
import importlib

my_env = os.environ

类的初始化:

class PyCompiler():
        def __init__(self, name_in, module, dep_list):
            self.file = name_in
            self.dep = dep_list
            self.module_name = module
            self.compiler_command = r"python setup.py  build_ext --inplace -c mingw32 "
            ''' Here it goes the creation of the setup.py file: '''
            self.set_setup()

还有类的方法:

def compile(self):
    command = self.compiler_command
    self.console = sp.call(command, env=my_env)

def include(self):
    module = __import__(self.module_name)
    return module

def set_setup(self):
    dependencies = ""
    for elem in self.dep:
        dependencies = dependencies + ",'"+elem+".c'"
    filename = "setup.py"
    target = open (filename, 'w')
    line1 = "from distutils.core import setup, Extension"
    line2 = "\n"
    line3 = "module1 = Extension('"
    line4 = self.module_name
    line5 = "', sources = ['"+self.file+"'"+dependencies+"])\n"
    line6 = "setup (name = 'PackageName',"   
    line7 = "version = '1.0',"
    line8 = "description = 'This is the code generated package.',"
    line9 = "ext_modules = [module1])"
    target.write(line1 + line2 + line3 + line4 + line5 + line6 + line7 + line8 + line9)
    target.close()

以及执行的代码:

TestCode = PyCompiler(file, module, [lib])
TestCode.compile()
test = TestCode.include()
  • file是要编译的C文件。
  • module是分配给创建的Python模块的名称。
  • [lib]是额外的C依赖项列表。

撰写回答