私が現在達成したいのは、返された組み合わせをソートすることを目的として、Pythonitertools
モジュール関数を微調整combinations
して、渡されたものをソートしてiterable
から組み合わせを作成することです。
私は初めて Python 拡張モジュールに取り組んでおり、これまでの唯一の経験は、Python 拡張モジュールのような "Hello World" を作成してコンパイルすることでしたが、いくつかのプログラミング言語での私の全体的なプログラミング経験が、この挑戦を成功させるために築き上げるのに十分な強固な基盤。
sorted()
渡された iterable をソートできる組み込みの Python 関数があることは知ってcombinations
いますが、拡張モジュールの C コード内から呼び出す方法がわかりません。
私はちょうど書き込もうとしましiterable = sorted(iterable);
たが、モジュールがコンパイルされても(警告付きで)、コンパイルされたモジュールのインポートは失敗しますImportError: cgitertools.cpython-36m-x86_64-linux-gnu.so: undefined symbol: sorted
私の質問は:
sorted()
Python 拡張モジュールの C コード内から(例として使用して) Pythons 組み込みメソッドを呼び出す方法は?
私が試したことと、それがうまくいかなかった理由のすべての詳細の下に:
combinations_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
combinationsobject *co;
Py_ssize_t n;
Py_ssize_t r;
PyObject *pool = NULL;
PyObject *iterable = NULL;
Py_ssize_t *indices = NULL;
Py_ssize_t i;
static char *kwargs[] = {"iterable", "r", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations", kwargs,
&iterable, &r))
return NULL;
// iterable.sort(); doesn't work ... cgitertoolsmodule.c:2398:13: error: request for member ‘sort’ in something not a structure or union
// iterable.__sort__(); doesn't work either with same error
// COMPILES, but gives ERROR on import in Python:
iterable = sorted(iterable);
$ python3.6 cgitertoolsmodule-setup.py build
running build
running build_ext
building 'cgitertools' extension
gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/include/python3.6m -c cgitertoolsmodule.c -o build/temp.linux-x86_64-3.6/cgitertoolsmodule.o
cgitertoolsmodule.c: In function ‘combinations_new’:
cgitertoolsmodule.c:2400:16: warning: implicit declaration of function ‘sorted’ [-Wimplicit-function-declaration]
iterable = sorted(iterable);
^
cgitertoolsmodule.c:2400:14: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
iterable = sorted(iterable);
^
gcc -pthread -shared build/temp.linux-x86_64-3.6/cgitertoolsmodule.o -o build/lib.linux-x86_64-3.6/cgitertools.cpython-36m-x86_64-linux-gnu.so
$ python3.6
Python 3.6.1 (default, Apr 18 2017, 23:00:41)
[GCC 5.4.1 20160904] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from cgitertools import combinations
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cgitertools.cpython-36m-x86_64-linux-gnu.so: undefined symbol: sorted