![](/img/trans.png)
[英]Python multiprocessing: call module with multiprocessing from another script with passing variable
[英]Passing a string from C to Python to multiprocessing without making an extra copy
我有一个嵌入Python 2.7解释器的C应用程序。 在我的程序中的某个时候,会生成一个可能很大的字符串( char*
),并且需要使用某些Python代码进行处理。 我使用PyObject_CallFunction
调用Python函数并将字符串作为参数传递。 然后,此Python函数使用multiprocessing
库在一个单独的进程中分析数据。
将字符串传递给Python函数将在Python str
对象中创建数据的副本。 我试图通过将buffer
对象传递给Python函数来避免这种额外的复制。 不幸的是,这会在解腌过程中在multiprocessing
处理过程中产生错误:
TypeError: buffer() takes at least 1 argument (0 given)
似乎可以对buffer
对象进行腌制,但不能对其进行腌制。
关于将char*
从C传递到multiprocessing
函数而不作额外复制的任何建议?
对我有用的方法:
在创建大C字符串之前,请使用Python为它分配内存:
PyObject *pystr = PyString_FromStringAndSize(NULL, size);
char *str = PyString_AS_STRING(pystr);
/* now fill <str> with <size> bytes */
这样,当需要将其传递给Python时,您不必创建副本:
PyObject *result = PyObject_CallFunctionObjArgs(callable, pystr, NULL);
/* or PyObject_CallFunction(callable, "O", pystr) if you prefer */
请注意,完成此操作后,您不应修改字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.