我正在尝试封装一些 C++ 神经网络代码,以便我拥有:
numpy -> double* -> armadillo
无论如何,我遇到了典型的情况:
ImportError: dynamic module does not define init function
显然我的distutils配置出了问题,以下是我的项目的MEW以防有人能找出错误所在:
setup.py
#!/usr/bin/env python build_ext --inplace
# -*- coding: utf-8 -*-
# to run:
# python setup.py build_ext --inplace
from distutils.core import setup, Extension
from Cython.Build import cythonize
setup(
name='My Test',
ext_modules = cythonize(Extension(
"test",
sources=["nnet_wrap.pyx", "nnet.cpp"],
libraries = ['armadillo'],
language="c++",
)))
nnet_wrap.pyx
import numpy as np
cimport numpy as np
cdef extern from "nnet.h":
void nnet_fit(int D, int N, double* X, double* Y)
class WrapNN:
def nnet_fit(self, np.ndarray[np.double_t, ndim=2] X):
X = np.ascontiguousarray(X)
cdef np.ndarray[np.double_t, ndim=1] y = np.zeros((len(X),), dtype=np.double)
nnet_fit(X.shape[1], X.shape[0], &X[0,0], &y[0])
return y
nnet.h
void nnet_fit(int D, int N, double* X, double* Y);
nnet.cpp
#include <armadillo>
using namespace arma;
void nnet_fit(int D, int N, double* X, double* Y)
{
mat _X(X, N, D, false);
// do work
vec _Y; // results
for(int i = 0; i < N; i++)
Y[i] = _Y[i];
}
我知道这有点hacky。不管怎样,它可以编译并生成一个test.so
文件,但是导入失败了:
$ python setup.py build_ext --inplace
$ python
>>> import test
ImportError: dynamic module does not define init function (inittest)
编辑: 根据要求提供更多信息:
$ readelf -Ws test.so | grep init
118: 0000000000003168 0 FUNC GLOBAL DEFAULT 9 _init
123: 000000000000ab90 160 FUNC WEAK DEFAULT 11 _ZN4arma3MatIdE9init_coldEv
126: 0000000000009ae0 4211 FUNC GLOBAL DEFAULT 11 initnnet_wrap
42: 00000000000036e0 79 FUNC LOCAL DEFAULT 11 _ZL30__Pyx_CyFunction_init_defaultsP22__pyx_CyFunctionObject
202: 000000000020f3e0 1 OBJECT LOCAL DEFAULT 24 _ZStL8__ioinit
211: 000000000020dce0 0 OBJECT LOCAL DEFAULT 17 __frame_dummy_init_array_entry
306: 0000000000009ae0 4211 FUNC GLOBAL DEFAULT 11 initnnet_wrap
330: 000000000000ab90 160 FUNC WEAK DEFAULT 11 _ZN4arma3MatIdE9init_coldEv
344: 0000000000003168 0 FUNC GLOBAL DEFAULT 9 _init
顺便提一下,我的Cython版本是来自于Ubuntu 14.04的,可能略微有点过时。我知道一些语法已经从distutils中改变了。如果您认为这可能会成为一个问题,请告诉我。
$ dpkg -s cython | grep Version
Version: 0.20.1+git90-g0e6e38e-1ubuntu2
readelf -Ws test.so | grep init
(或nm -gC test.so | grep init
)的输出是什么? - Andrea Corbellini