我有一个 Python 脚本和一个 C 程序,我需要从多次调用 C 程序的 Python 脚本传递大量数据。现在我让用户选择用 ASCII 文件或二进制文件传递它们,但两者都很慢且无用(我的意思是如果你想存储数据,文件很有用,但我在最后删除了这些文件脚本)。
os.system
不起作用,参数太多,因为 C 程序也使用文件将数据返回给 Python,但这是少得多的数据。
我想知道我可以使用什么来加快这种交流。将文件写入 RAM 磁盘?如果可以,我该怎么做?
我听说可以使用 ctypes 从 DLL 调用函数,但不知道如何将我的程序编译为 DLL(我在 Windows 7 64 上使用 wxdevc+)。 或者包装一下,但还是不知道能不能用,效率高不高。
数据是 3D 网格的顶点。
我在另一个程序(blender(开源)中运行 Python 脚本,并且被调用多次(通常超过 500 次),因为它在一个循环中。脚本发送顶点信息(1 int
index and 3 float coords) 给程序,程序应该返回很多顶点(只有 int index,因为我可以用 Python 找到对应的顶点)。
所以这不是交互式的,它更像是一个函数(但它是用 C 语言编写的)。我正在编写的脚本 + C 程序(即 blender 的附加组件)应该是跨平台的,因为它将被重新分发。
该程序实际上是用 C 编写的,从 Python 我可以知道包含顶点数据的结构在内存中的地址。如果只有我知道如何做到这一点,最好只向 C 程序传递一个地址,然后从那里找到所有其他顶点(存储在列表中)。
但据我所知,我无法访问另一个程序的内存空间,我不知道是用管道调用程序还是初始化一个新线程或在脚本中运行(即实际上在 Blender 线程下运行)
Here is the source blender/source/blender/makesdna/DNA_meshdata_types.h
应该是结构定义
最佳答案
管道是显而易见的方式;如果您的 c 程序接受来自标准输入的输入,您可以使用 Popen
。这不会像您在编辑中所说的那样创建“线程”;它创建了一个具有独立内存的全新进程:
from subprocess import Popen, PIPE
input = "some input"
cproc = Popen("c_prog", stdin=PIPE, stdout=PIPE)
out, err = cproc.communicate(input)
这是一个更详细的例子。首先,一个简单的 c 程序来回显 stdin:
#include<stdio.h>
#include<stdlib.h>
#define BUFMAX 100
int main() {
char buffer[BUFMAX + 1];
char *bp = buffer;
int c;
FILE *in;
while (EOF != (c = fgetc(stdin)) && (bp - buffer) < BUFMAX) {
*bp++ = c;
}
*bp = 0; // Null-terminate the string
printf("%s", buffer);
}
然后是一个 python 程序,将输入(在本例中是从 argv)通过管道传输到上面:
from subprocess import Popen, PIPE
from sys import argv
input = ' '.join(argv[1:])
if not input: input = "no arguments given"
cproc = Popen("./c_prog", stdin=PIPE, stdout=PIPE)
out, err = cproc.communicate(input)
print "output:", out
print "errors:", err
如果你不打算在没有 python 前端的情况下使用 c 程序,那么你最好内联一个 c 函数,也许使用 instant
。
from instant import inline
c_code = """
[ ... some c code ... ] //see the below page for a more complete example.
"""
c_func = inline(c_code)
正如 Joe 指出的那样,您还可以在 c: Extending Python with C or C++ 中编写一个 python 模块
这个答案讨论了结合 c 和 python 的其他方法:How do I connect a Python and a C program?
编辑:根据您的编辑,听起来您真的应该创建一个 cpython 扩展。如果你想要一些示例代码,请告诉我;但是完整的解释会导致答案过长。请参阅上面的链接(扩展 Python...),了解您需要了解的一切。
关于python - 将多条数据从 Python 传递到 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4961267/