![](/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.