Pro*_*ala 7 c++ python ctypes numpy
抱歉还有一个关于dynamic module does not define init function. 我确实通过了较旧的问题,但我没有找到一个专门解决我的案子的问题。
我有一个 C++ 库,它应该将几个函数导出到 python(比如在extern "C" {}block 中定义的 ~5 个函数)。当我每次导入库时重新编译它时,它工作得很好。但是,如果我在没有重新编译的情况下导入它,则会出现错误ImportError: dynamic module does not define init function (initmylib)
重现相同行为(错误)的非常简化的示例如下所示:
文件中的 C++ 库代码 mylib.cpp
#include <math.h>
// there are some internal C++ functions and classes
// which are not exported, but used in exported functions
extern "C"{
// one of the functions which should be accessible from python
void oscilator( double dt, int n, double * abuff, double * bbuff ){
double a = abuff[0];
double b = bbuff[0];
for (int i=1; i<n; i++){
a = a - b*dt;
b = b + a*dt;
abuff[i] = a;
bbuff[i] = b;
}
}
// there are also other functions but let's keep this example simple
// int initmylib( ){ return 0; } // some junk ... if this makes ctypes happy ?
}
Run Code Online (Sandbox Code Playgroud)
mylib.pyC++ 库的python 变形器mylib.cpp:
import numpy as np
from ctypes import c_int, c_double
import ctypes
import os
name='mylib'
ext='.so' # if compited on linux .so on windows .dll
def recompile(
LFLAGS="",
#FFLAGS="-Og -g -Wall"
FFLAGS="-std=c++11 -O3 -ffast-math -ftree-vectorize"
):
import os
print " ===== COMPILATION OF : "+name+".cpp"
print os.getcwd()
os.system("g++ "+FFLAGS+" -c -fPIC "+name+".cpp -o "+name+".o"+LFLAGS)
os.system("g++ "+FFLAGS+" -shared -Wl,-soname,"+name+ext+" -o "+name+ext+" "+name+".o"+LFLAGS)
# this will recompile the library if somebody delete it
if not os.path.exists("./"+name+ext ):
recompile()
lib = ctypes.CDLL("./"+name+ext )
array1d = np.ctypeslib.ndpointer(dtype=np.double, ndim=1, flags='CONTIGUOUS')
# void oscilator( double dt, int n, double * abuff, double * bbuff )
lib.oscilator.argtypes = [ c_double, c_int, array1d, array1d ]
lib.oscilator.restype = None
def oscilator( dt, a, b ):
n = len(a)
lib.oscilator( dt, n, a, b )
Run Code Online (Sandbox Code Playgroud)
test.py导入的python程序mylib
import os
from pylab import *
from basUtils import *
# this will delete all compiled files of the library to force recompilation
def makeclean( ):
[ os.remove(f) for f in os.listdir(".") if f.endswith(".so") ]
[ os.remove(f) for f in os.listdir(".") if f.endswith(".o") ]
[ os.remove(f) for f in os.listdir(".") if f.endswith(".pyc") ]
# if I do makeclean() every time it works, if I do not it does not
#makeclean( )
import mylib
a=zeros(100)
b=zeros(100)
a[0] = 1
mylib.oscilator( 0.1, a, b )
plot( a )
plot( b )
show()
Run Code Online (Sandbox Code Playgroud)
我还试图通过在上面的代码中添加一些int initmylib( ){ return 0; }函数来使 ctypes 满意mylib.cpp。但是这会产生错误SystemError: dynamic module not initialized properly
当我从 scipy 讲义编译cos_doubles示例时,我没有这个问题。但是,此示例仅适用于如果我只想导入一个与库名称同名的函数。我想要更一般的东西。
尝试运行import imp; print imp.find_module('mylib')[1]。你对它选择 mylib.so 而不是 mylib.py 感到惊讶吗?解释器期望 mylib.so 是一个扩展模块,对于 CPython 2.x 应该定义一个名为initmylib. 为避免意外尝试导入共享库,请将名称更改为 _mylib.so 或 mylib.1.0.so 之类的名称 - 或者只是将文件保存在不在sys.path.
请注意,Windows 扩展模块是 DLL,但具有 .pyd 扩展名而不是 .dll。所以import mylib不会尝试加载 mylib.dll。