使用Python解释器编译Windows代码下的C++代码

2024-03-28 22:07:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我的环境是:

Windows 7。 pydevide(eclipse)。 Python。在

我想编译和测试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文件:

^{pr2}$

如果我启动这个脚本,我会得到:

output

也就是说我在方法上出错了PyCompiler.compile,自从subprocess.call不是1。在

你能就这个问题提供一些指导吗?在

你知道还有别的方法吗?在


Tags: 文件方法代码test脚本add环境is
1条回答
网友
1楼 · 发布于 2024-03-28 22:07:37

实际上,我通过安装MinGW并使用它编译C代码来解决这个问题。我的python代码是:

import subprocess as sp
import os
import importlib

my_env = os.environ

类初始化:

^{pr2}$

和类方法:

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依赖项的列表。在

相关问题 更多 >