cfuncs.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  1. #!/usr/bin/env python3
  2. """
  3. C declarations, CPP macros, and C functions for f2py2e.
  4. Only required declarations/macros/functions will be used.
  5. Copyright 1999,2000 Pearu Peterson all rights reserved,
  6. Pearu Peterson <pearu@ioc.ee>
  7. Permission to use, modify, and distribute this software is given under the
  8. terms of the NumPy License.
  9. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  10. $Date: 2005/05/06 11:42:34 $
  11. Pearu Peterson
  12. """
  13. import sys
  14. import copy
  15. from . import __version__
  16. f2py_version = __version__.version
  17. errmess = sys.stderr.write
  18. ##################### Definitions ##################
  19. outneeds = {'includes0': [], 'includes': [], 'typedefs': [], 'typedefs_generated': [],
  20. 'userincludes': [],
  21. 'cppmacros': [], 'cfuncs': [], 'callbacks': [], 'f90modhooks': [],
  22. 'commonhooks': []}
  23. needs = {}
  24. includes0 = {'includes0': '/*need_includes0*/'}
  25. includes = {'includes': '/*need_includes*/'}
  26. userincludes = {'userincludes': '/*need_userincludes*/'}
  27. typedefs = {'typedefs': '/*need_typedefs*/'}
  28. typedefs_generated = {'typedefs_generated': '/*need_typedefs_generated*/'}
  29. cppmacros = {'cppmacros': '/*need_cppmacros*/'}
  30. cfuncs = {'cfuncs': '/*need_cfuncs*/'}
  31. callbacks = {'callbacks': '/*need_callbacks*/'}
  32. f90modhooks = {'f90modhooks': '/*need_f90modhooks*/',
  33. 'initf90modhooksstatic': '/*initf90modhooksstatic*/',
  34. 'initf90modhooksdynamic': '/*initf90modhooksdynamic*/',
  35. }
  36. commonhooks = {'commonhooks': '/*need_commonhooks*/',
  37. 'initcommonhooks': '/*need_initcommonhooks*/',
  38. }
  39. ############ Includes ###################
  40. includes0['math.h'] = '#include <math.h>'
  41. includes0['string.h'] = '#include <string.h>'
  42. includes0['setjmp.h'] = '#include <setjmp.h>'
  43. includes['Python.h'] = '#include "Python.h"'
  44. needs['arrayobject.h'] = ['Python.h']
  45. includes['arrayobject.h'] = '''#define PY_ARRAY_UNIQUE_SYMBOL PyArray_API
  46. #include "arrayobject.h"'''
  47. includes['arrayobject.h'] = '#include "fortranobject.h"'
  48. includes['stdarg.h'] = '#include <stdarg.h>'
  49. ############# Type definitions ###############
  50. typedefs['unsigned_char'] = 'typedef unsigned char unsigned_char;'
  51. typedefs['unsigned_short'] = 'typedef unsigned short unsigned_short;'
  52. typedefs['unsigned_long'] = 'typedef unsigned long unsigned_long;'
  53. typedefs['signed_char'] = 'typedef signed char signed_char;'
  54. typedefs['long_long'] = """\
  55. #ifdef _WIN32
  56. typedef __int64 long_long;
  57. #else
  58. typedef long long long_long;
  59. typedef unsigned long long unsigned_long_long;
  60. #endif
  61. """
  62. typedefs['unsigned_long_long'] = """\
  63. #ifdef _WIN32
  64. typedef __uint64 long_long;
  65. #else
  66. typedef unsigned long long unsigned_long_long;
  67. #endif
  68. """
  69. typedefs['long_double'] = """\
  70. #ifndef _LONG_DOUBLE
  71. typedef long double long_double;
  72. #endif
  73. """
  74. typedefs[
  75. 'complex_long_double'] = 'typedef struct {long double r,i;} complex_long_double;'
  76. typedefs['complex_float'] = 'typedef struct {float r,i;} complex_float;'
  77. typedefs['complex_double'] = 'typedef struct {double r,i;} complex_double;'
  78. typedefs['string'] = """typedef char * string;"""
  79. ############### CPP macros ####################
  80. cppmacros['CFUNCSMESS'] = """\
  81. #ifdef DEBUGCFUNCS
  82. #define CFUNCSMESS(mess) fprintf(stderr,\"debug-capi:\"mess);
  83. #define CFUNCSMESSPY(mess,obj) CFUNCSMESS(mess) \\
  84. PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\
  85. fprintf(stderr,\"\\n\");
  86. #else
  87. #define CFUNCSMESS(mess)
  88. #define CFUNCSMESSPY(mess,obj)
  89. #endif
  90. """
  91. cppmacros['F_FUNC'] = """\
  92. #if defined(PREPEND_FORTRAN)
  93. #if defined(NO_APPEND_FORTRAN)
  94. #if defined(UPPERCASE_FORTRAN)
  95. #define F_FUNC(f,F) _##F
  96. #else
  97. #define F_FUNC(f,F) _##f
  98. #endif
  99. #else
  100. #if defined(UPPERCASE_FORTRAN)
  101. #define F_FUNC(f,F) _##F##_
  102. #else
  103. #define F_FUNC(f,F) _##f##_
  104. #endif
  105. #endif
  106. #else
  107. #if defined(NO_APPEND_FORTRAN)
  108. #if defined(UPPERCASE_FORTRAN)
  109. #define F_FUNC(f,F) F
  110. #else
  111. #define F_FUNC(f,F) f
  112. #endif
  113. #else
  114. #if defined(UPPERCASE_FORTRAN)
  115. #define F_FUNC(f,F) F##_
  116. #else
  117. #define F_FUNC(f,F) f##_
  118. #endif
  119. #endif
  120. #endif
  121. #if defined(UNDERSCORE_G77)
  122. #define F_FUNC_US(f,F) F_FUNC(f##_,F##_)
  123. #else
  124. #define F_FUNC_US(f,F) F_FUNC(f,F)
  125. #endif
  126. """
  127. cppmacros['F_WRAPPEDFUNC'] = """\
  128. #if defined(PREPEND_FORTRAN)
  129. #if defined(NO_APPEND_FORTRAN)
  130. #if defined(UPPERCASE_FORTRAN)
  131. #define F_WRAPPEDFUNC(f,F) _F2PYWRAP##F
  132. #else
  133. #define F_WRAPPEDFUNC(f,F) _f2pywrap##f
  134. #endif
  135. #else
  136. #if defined(UPPERCASE_FORTRAN)
  137. #define F_WRAPPEDFUNC(f,F) _F2PYWRAP##F##_
  138. #else
  139. #define F_WRAPPEDFUNC(f,F) _f2pywrap##f##_
  140. #endif
  141. #endif
  142. #else
  143. #if defined(NO_APPEND_FORTRAN)
  144. #if defined(UPPERCASE_FORTRAN)
  145. #define F_WRAPPEDFUNC(f,F) F2PYWRAP##F
  146. #else
  147. #define F_WRAPPEDFUNC(f,F) f2pywrap##f
  148. #endif
  149. #else
  150. #if defined(UPPERCASE_FORTRAN)
  151. #define F_WRAPPEDFUNC(f,F) F2PYWRAP##F##_
  152. #else
  153. #define F_WRAPPEDFUNC(f,F) f2pywrap##f##_
  154. #endif
  155. #endif
  156. #endif
  157. #if defined(UNDERSCORE_G77)
  158. #define F_WRAPPEDFUNC_US(f,F) F_WRAPPEDFUNC(f##_,F##_)
  159. #else
  160. #define F_WRAPPEDFUNC_US(f,F) F_WRAPPEDFUNC(f,F)
  161. #endif
  162. """
  163. cppmacros['F_MODFUNC'] = """\
  164. #if defined(F90MOD2CCONV1) /*E.g. Compaq Fortran */
  165. #if defined(NO_APPEND_FORTRAN)
  166. #define F_MODFUNCNAME(m,f) $ ## m ## $ ## f
  167. #else
  168. #define F_MODFUNCNAME(m,f) $ ## m ## $ ## f ## _
  169. #endif
  170. #endif
  171. #if defined(F90MOD2CCONV2) /*E.g. IBM XL Fortran, not tested though */
  172. #if defined(NO_APPEND_FORTRAN)
  173. #define F_MODFUNCNAME(m,f) __ ## m ## _MOD_ ## f
  174. #else
  175. #define F_MODFUNCNAME(m,f) __ ## m ## _MOD_ ## f ## _
  176. #endif
  177. #endif
  178. #if defined(F90MOD2CCONV3) /*E.g. MIPSPro Compilers */
  179. #if defined(NO_APPEND_FORTRAN)
  180. #define F_MODFUNCNAME(m,f) f ## .in. ## m
  181. #else
  182. #define F_MODFUNCNAME(m,f) f ## .in. ## m ## _
  183. #endif
  184. #endif
  185. /*
  186. #if defined(UPPERCASE_FORTRAN)
  187. #define F_MODFUNC(m,M,f,F) F_MODFUNCNAME(M,F)
  188. #else
  189. #define F_MODFUNC(m,M,f,F) F_MODFUNCNAME(m,f)
  190. #endif
  191. */
  192. #define F_MODFUNC(m,f) (*(f2pymodstruct##m##.##f))
  193. """
  194. cppmacros['SWAPUNSAFE'] = """\
  195. #define SWAP(a,b) (size_t)(a) = ((size_t)(a) ^ (size_t)(b));\\
  196. (size_t)(b) = ((size_t)(a) ^ (size_t)(b));\\
  197. (size_t)(a) = ((size_t)(a) ^ (size_t)(b))
  198. """
  199. cppmacros['SWAP'] = """\
  200. #define SWAP(a,b,t) {\\
  201. t *c;\\
  202. c = a;\\
  203. a = b;\\
  204. b = c;}
  205. """
  206. # cppmacros['ISCONTIGUOUS']='#define ISCONTIGUOUS(m) (PyArray_FLAGS(m) &
  207. # NPY_ARRAY_C_CONTIGUOUS)'
  208. cppmacros['PRINTPYOBJERR'] = """\
  209. #define PRINTPYOBJERR(obj)\\
  210. fprintf(stderr,\"#modulename#.error is related to \");\\
  211. PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\
  212. fprintf(stderr,\"\\n\");
  213. """
  214. cppmacros['MINMAX'] = """\
  215. #ifndef max
  216. #define max(a,b) ((a > b) ? (a) : (b))
  217. #endif
  218. #ifndef min
  219. #define min(a,b) ((a < b) ? (a) : (b))
  220. #endif
  221. #ifndef MAX
  222. #define MAX(a,b) ((a > b) ? (a) : (b))
  223. #endif
  224. #ifndef MIN
  225. #define MIN(a,b) ((a < b) ? (a) : (b))
  226. #endif
  227. """
  228. needs['len..'] = ['f2py_size']
  229. cppmacros['len..'] = """\
  230. #define rank(var) var ## _Rank
  231. #define shape(var,dim) var ## _Dims[dim]
  232. #define old_rank(var) (PyArray_NDIM((PyArrayObject *)(capi_ ## var ## _tmp)))
  233. #define old_shape(var,dim) PyArray_DIM(((PyArrayObject *)(capi_ ## var ## _tmp)),dim)
  234. #define fshape(var,dim) shape(var,rank(var)-dim-1)
  235. #define len(var) shape(var,0)
  236. #define flen(var) fshape(var,0)
  237. #define old_size(var) PyArray_SIZE((PyArrayObject *)(capi_ ## var ## _tmp))
  238. /* #define index(i) capi_i ## i */
  239. #define slen(var) capi_ ## var ## _len
  240. #define size(var, ...) f2py_size((PyArrayObject *)(capi_ ## var ## _tmp), ## __VA_ARGS__, -1)
  241. """
  242. needs['f2py_size'] = ['stdarg.h']
  243. cfuncs['f2py_size'] = """\
  244. static int f2py_size(PyArrayObject* var, ...)
  245. {
  246. npy_int sz = 0;
  247. npy_int dim;
  248. npy_int rank;
  249. va_list argp;
  250. va_start(argp, var);
  251. dim = va_arg(argp, npy_int);
  252. if (dim==-1)
  253. {
  254. sz = PyArray_SIZE(var);
  255. }
  256. else
  257. {
  258. rank = PyArray_NDIM(var);
  259. if (dim>=1 && dim<=rank)
  260. sz = PyArray_DIM(var, dim-1);
  261. else
  262. fprintf(stderr, \"f2py_size: 2nd argument value=%d fails to satisfy 1<=value<=%d. Result will be 0.\\n\", dim, rank);
  263. }
  264. va_end(argp);
  265. return sz;
  266. }
  267. """
  268. cppmacros[
  269. 'pyobj_from_char1'] = '#define pyobj_from_char1(v) (PyLong_FromLong(v))'
  270. cppmacros[
  271. 'pyobj_from_short1'] = '#define pyobj_from_short1(v) (PyLong_FromLong(v))'
  272. needs['pyobj_from_int1'] = ['signed_char']
  273. cppmacros['pyobj_from_int1'] = '#define pyobj_from_int1(v) (PyLong_FromLong(v))'
  274. cppmacros[
  275. 'pyobj_from_long1'] = '#define pyobj_from_long1(v) (PyLong_FromLong(v))'
  276. needs['pyobj_from_long_long1'] = ['long_long']
  277. cppmacros['pyobj_from_long_long1'] = """\
  278. #ifdef HAVE_LONG_LONG
  279. #define pyobj_from_long_long1(v) (PyLong_FromLongLong(v))
  280. #else
  281. #warning HAVE_LONG_LONG is not available. Redefining pyobj_from_long_long.
  282. #define pyobj_from_long_long1(v) (PyLong_FromLong(v))
  283. #endif
  284. """
  285. needs['pyobj_from_long_double1'] = ['long_double']
  286. cppmacros[
  287. 'pyobj_from_long_double1'] = '#define pyobj_from_long_double1(v) (PyFloat_FromDouble(v))'
  288. cppmacros[
  289. 'pyobj_from_double1'] = '#define pyobj_from_double1(v) (PyFloat_FromDouble(v))'
  290. cppmacros[
  291. 'pyobj_from_float1'] = '#define pyobj_from_float1(v) (PyFloat_FromDouble(v))'
  292. needs['pyobj_from_complex_long_double1'] = ['complex_long_double']
  293. cppmacros[
  294. 'pyobj_from_complex_long_double1'] = '#define pyobj_from_complex_long_double1(v) (PyComplex_FromDoubles(v.r,v.i))'
  295. needs['pyobj_from_complex_double1'] = ['complex_double']
  296. cppmacros[
  297. 'pyobj_from_complex_double1'] = '#define pyobj_from_complex_double1(v) (PyComplex_FromDoubles(v.r,v.i))'
  298. needs['pyobj_from_complex_float1'] = ['complex_float']
  299. cppmacros[
  300. 'pyobj_from_complex_float1'] = '#define pyobj_from_complex_float1(v) (PyComplex_FromDoubles(v.r,v.i))'
  301. needs['pyobj_from_string1'] = ['string']
  302. cppmacros[
  303. 'pyobj_from_string1'] = '#define pyobj_from_string1(v) (PyUnicode_FromString((char *)v))'
  304. needs['pyobj_from_string1size'] = ['string']
  305. cppmacros[
  306. 'pyobj_from_string1size'] = '#define pyobj_from_string1size(v,len) (PyUnicode_FromStringAndSize((char *)v, len))'
  307. needs['TRYPYARRAYTEMPLATE'] = ['PRINTPYOBJERR']
  308. cppmacros['TRYPYARRAYTEMPLATE'] = """\
  309. /* New SciPy */
  310. #define TRYPYARRAYTEMPLATECHAR case NPY_STRING: *(char *)(PyArray_DATA(arr))=*v; break;
  311. #define TRYPYARRAYTEMPLATELONG case NPY_LONG: *(long *)(PyArray_DATA(arr))=*v; break;
  312. #define TRYPYARRAYTEMPLATEOBJECT case NPY_OBJECT: PyArray_SETITEM(arr,PyArray_DATA(arr),pyobj_from_ ## ctype ## 1(*v)); break;
  313. #define TRYPYARRAYTEMPLATE(ctype,typecode) \\
  314. PyArrayObject *arr = NULL;\\
  315. if (!obj) return -2;\\
  316. if (!PyArray_Check(obj)) return -1;\\
  317. if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,\"TRYPYARRAYTEMPLATE:\");PRINTPYOBJERR(obj);return 0;}\\
  318. if (PyArray_DESCR(arr)->type==typecode) {*(ctype *)(PyArray_DATA(arr))=*v; return 1;}\\
  319. switch (PyArray_TYPE(arr)) {\\
  320. case NPY_DOUBLE: *(double *)(PyArray_DATA(arr))=*v; break;\\
  321. case NPY_INT: *(int *)(PyArray_DATA(arr))=*v; break;\\
  322. case NPY_LONG: *(long *)(PyArray_DATA(arr))=*v; break;\\
  323. case NPY_FLOAT: *(float *)(PyArray_DATA(arr))=*v; break;\\
  324. case NPY_CDOUBLE: *(double *)(PyArray_DATA(arr))=*v; break;\\
  325. case NPY_CFLOAT: *(float *)(PyArray_DATA(arr))=*v; break;\\
  326. case NPY_BOOL: *(npy_bool *)(PyArray_DATA(arr))=(*v!=0); break;\\
  327. case NPY_UBYTE: *(unsigned char *)(PyArray_DATA(arr))=*v; break;\\
  328. case NPY_BYTE: *(signed char *)(PyArray_DATA(arr))=*v; break;\\
  329. case NPY_SHORT: *(short *)(PyArray_DATA(arr))=*v; break;\\
  330. case NPY_USHORT: *(npy_ushort *)(PyArray_DATA(arr))=*v; break;\\
  331. case NPY_UINT: *(npy_uint *)(PyArray_DATA(arr))=*v; break;\\
  332. case NPY_ULONG: *(npy_ulong *)(PyArray_DATA(arr))=*v; break;\\
  333. case NPY_LONGLONG: *(npy_longlong *)(PyArray_DATA(arr))=*v; break;\\
  334. case NPY_ULONGLONG: *(npy_ulonglong *)(PyArray_DATA(arr))=*v; break;\\
  335. case NPY_LONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=*v; break;\\
  336. case NPY_CLONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=*v; break;\\
  337. case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_ ## ctype ## 1(*v)); break;\\
  338. default: return -2;\\
  339. };\\
  340. return 1
  341. """
  342. needs['TRYCOMPLEXPYARRAYTEMPLATE'] = ['PRINTPYOBJERR']
  343. cppmacros['TRYCOMPLEXPYARRAYTEMPLATE'] = """\
  344. #define TRYCOMPLEXPYARRAYTEMPLATEOBJECT case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_complex_ ## ctype ## 1((*v))); break;
  345. #define TRYCOMPLEXPYARRAYTEMPLATE(ctype,typecode)\\
  346. PyArrayObject *arr = NULL;\\
  347. if (!obj) return -2;\\
  348. if (!PyArray_Check(obj)) return -1;\\
  349. if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,\"TRYCOMPLEXPYARRAYTEMPLATE:\");PRINTPYOBJERR(obj);return 0;}\\
  350. if (PyArray_DESCR(arr)->type==typecode) {\\
  351. *(ctype *)(PyArray_DATA(arr))=(*v).r;\\
  352. *(ctype *)(PyArray_DATA(arr)+sizeof(ctype))=(*v).i;\\
  353. return 1;\\
  354. }\\
  355. switch (PyArray_TYPE(arr)) {\\
  356. case NPY_CDOUBLE: *(double *)(PyArray_DATA(arr))=(*v).r;*(double *)(PyArray_DATA(arr)+sizeof(double))=(*v).i;break;\\
  357. case NPY_CFLOAT: *(float *)(PyArray_DATA(arr))=(*v).r;*(float *)(PyArray_DATA(arr)+sizeof(float))=(*v).i;break;\\
  358. case NPY_DOUBLE: *(double *)(PyArray_DATA(arr))=(*v).r; break;\\
  359. case NPY_LONG: *(long *)(PyArray_DATA(arr))=(*v).r; break;\\
  360. case NPY_FLOAT: *(float *)(PyArray_DATA(arr))=(*v).r; break;\\
  361. case NPY_INT: *(int *)(PyArray_DATA(arr))=(*v).r; break;\\
  362. case NPY_SHORT: *(short *)(PyArray_DATA(arr))=(*v).r; break;\\
  363. case NPY_UBYTE: *(unsigned char *)(PyArray_DATA(arr))=(*v).r; break;\\
  364. case NPY_BYTE: *(signed char *)(PyArray_DATA(arr))=(*v).r; break;\\
  365. case NPY_BOOL: *(npy_bool *)(PyArray_DATA(arr))=((*v).r!=0 && (*v).i!=0); break;\\
  366. case NPY_USHORT: *(npy_ushort *)(PyArray_DATA(arr))=(*v).r; break;\\
  367. case NPY_UINT: *(npy_uint *)(PyArray_DATA(arr))=(*v).r; break;\\
  368. case NPY_ULONG: *(npy_ulong *)(PyArray_DATA(arr))=(*v).r; break;\\
  369. case NPY_LONGLONG: *(npy_longlong *)(PyArray_DATA(arr))=(*v).r; break;\\
  370. case NPY_ULONGLONG: *(npy_ulonglong *)(PyArray_DATA(arr))=(*v).r; break;\\
  371. case NPY_LONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=(*v).r; break;\\
  372. case NPY_CLONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=(*v).r;*(npy_longdouble *)(PyArray_DATA(arr)+sizeof(npy_longdouble))=(*v).i;break;\\
  373. case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_complex_ ## ctype ## 1((*v))); break;\\
  374. default: return -2;\\
  375. };\\
  376. return -1;
  377. """
  378. # cppmacros['NUMFROMARROBJ']="""\
  379. # define NUMFROMARROBJ(typenum,ctype) \\
  380. # if (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\
  381. # else arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\
  382. # if (arr) {\\
  383. # if (PyArray_TYPE(arr)==NPY_OBJECT) {\\
  384. # if (!ctype ## _from_pyobj(v,(PyArray_DESCR(arr)->getitem)(PyArray_DATA(arr)),\"\"))\\
  385. # goto capi_fail;\\
  386. # } else {\\
  387. # (PyArray_DESCR(arr)->cast[typenum])(PyArray_DATA(arr),1,(char*)v,1,1);\\
  388. # }\\
  389. # if ((PyObject *)arr != obj) { Py_DECREF(arr); }\\
  390. # return 1;\\
  391. # }
  392. # """
  393. # XXX: Note that CNUMFROMARROBJ is identical with NUMFROMARROBJ
  394. # cppmacros['CNUMFROMARROBJ']="""\
  395. # define CNUMFROMARROBJ(typenum,ctype) \\
  396. # if (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\
  397. # else arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\
  398. # if (arr) {\\
  399. # if (PyArray_TYPE(arr)==NPY_OBJECT) {\\
  400. # if (!ctype ## _from_pyobj(v,(PyArray_DESCR(arr)->getitem)(PyArray_DATA(arr)),\"\"))\\
  401. # goto capi_fail;\\
  402. # } else {\\
  403. # (PyArray_DESCR(arr)->cast[typenum])((void *)(PyArray_DATA(arr)),1,(void *)(v),1,1);\\
  404. # }\\
  405. # if ((PyObject *)arr != obj) { Py_DECREF(arr); }\\
  406. # return 1;\\
  407. # }
  408. # """
  409. needs['GETSTRFROMPYTUPLE'] = ['STRINGCOPYN', 'PRINTPYOBJERR']
  410. cppmacros['GETSTRFROMPYTUPLE'] = """\
  411. #define GETSTRFROMPYTUPLE(tuple,index,str,len) {\\
  412. PyObject *rv_cb_str = PyTuple_GetItem((tuple),(index));\\
  413. if (rv_cb_str == NULL)\\
  414. goto capi_fail;\\
  415. if (PyBytes_Check(rv_cb_str)) {\\
  416. str[len-1]='\\0';\\
  417. STRINGCOPYN((str),PyBytes_AS_STRING((PyBytesObject*)rv_cb_str),(len));\\
  418. } else {\\
  419. PRINTPYOBJERR(rv_cb_str);\\
  420. PyErr_SetString(#modulename#_error,\"string object expected\");\\
  421. goto capi_fail;\\
  422. }\\
  423. }
  424. """
  425. cppmacros['GETSCALARFROMPYTUPLE'] = """\
  426. #define GETSCALARFROMPYTUPLE(tuple,index,var,ctype,mess) {\\
  427. if ((capi_tmp = PyTuple_GetItem((tuple),(index)))==NULL) goto capi_fail;\\
  428. if (!(ctype ## _from_pyobj((var),capi_tmp,mess)))\\
  429. goto capi_fail;\\
  430. }
  431. """
  432. cppmacros['FAILNULL'] = """\\
  433. #define FAILNULL(p) do { \\
  434. if ((p) == NULL) { \\
  435. PyErr_SetString(PyExc_MemoryError, "NULL pointer found"); \\
  436. goto capi_fail; \\
  437. } \\
  438. } while (0)
  439. """
  440. needs['MEMCOPY'] = ['string.h', 'FAILNULL']
  441. cppmacros['MEMCOPY'] = """\
  442. #define MEMCOPY(to,from,n)\\
  443. do { FAILNULL(to); FAILNULL(from); (void)memcpy(to,from,n); } while (0)
  444. """
  445. cppmacros['STRINGMALLOC'] = """\
  446. #define STRINGMALLOC(str,len)\\
  447. if ((str = (string)malloc(sizeof(char)*(len+1))) == NULL) {\\
  448. PyErr_SetString(PyExc_MemoryError, \"out of memory\");\\
  449. goto capi_fail;\\
  450. } else {\\
  451. (str)[len] = '\\0';\\
  452. }
  453. """
  454. cppmacros['STRINGFREE'] = """\
  455. #define STRINGFREE(str) do {if (!(str == NULL)) free(str);} while (0)
  456. """
  457. needs['STRINGCOPYN'] = ['string.h', 'FAILNULL']
  458. cppmacros['STRINGCOPYN'] = """\
  459. #define STRINGCOPYN(to,from,buf_size) \\
  460. do { \\
  461. int _m = (buf_size); \\
  462. char *_to = (to); \\
  463. char *_from = (from); \\
  464. FAILNULL(_to); FAILNULL(_from); \\
  465. (void)strncpy(_to, _from, sizeof(char)*_m); \\
  466. _to[_m-1] = '\\0'; \\
  467. /* Padding with spaces instead of nulls */ \\
  468. for (_m -= 2; _m >= 0 && _to[_m] == '\\0'; _m--) { \\
  469. _to[_m] = ' '; \\
  470. } \\
  471. } while (0)
  472. """
  473. needs['STRINGCOPY'] = ['string.h', 'FAILNULL']
  474. cppmacros['STRINGCOPY'] = """\
  475. #define STRINGCOPY(to,from)\\
  476. do { FAILNULL(to); FAILNULL(from); (void)strcpy(to,from); } while (0)
  477. """
  478. cppmacros['CHECKGENERIC'] = """\
  479. #define CHECKGENERIC(check,tcheck,name) \\
  480. if (!(check)) {\\
  481. PyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\
  482. /*goto capi_fail;*/\\
  483. } else """
  484. cppmacros['CHECKARRAY'] = """\
  485. #define CHECKARRAY(check,tcheck,name) \\
  486. if (!(check)) {\\
  487. PyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\
  488. /*goto capi_fail;*/\\
  489. } else """
  490. cppmacros['CHECKSTRING'] = """\
  491. #define CHECKSTRING(check,tcheck,name,show,var)\\
  492. if (!(check)) {\\
  493. char errstring[256];\\
  494. sprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, slen(var), var);\\
  495. PyErr_SetString(#modulename#_error, errstring);\\
  496. /*goto capi_fail;*/\\
  497. } else """
  498. cppmacros['CHECKSCALAR'] = """\
  499. #define CHECKSCALAR(check,tcheck,name,show,var)\\
  500. if (!(check)) {\\
  501. char errstring[256];\\
  502. sprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, var);\\
  503. PyErr_SetString(#modulename#_error,errstring);\\
  504. /*goto capi_fail;*/\\
  505. } else """
  506. # cppmacros['CHECKDIMS']="""\
  507. # define CHECKDIMS(dims,rank) \\
  508. # for (int i=0;i<(rank);i++)\\
  509. # if (dims[i]<0) {\\
  510. # fprintf(stderr,\"Unspecified array argument requires a complete dimension specification.\\n\");\\
  511. # goto capi_fail;\\
  512. # }
  513. # """
  514. cppmacros[
  515. 'ARRSIZE'] = '#define ARRSIZE(dims,rank) (_PyArray_multiply_list(dims,rank))'
  516. cppmacros['OLDPYNUM'] = """\
  517. #ifdef OLDPYNUM
  518. #error You need to install NumPy version 0.13 or higher. See https://scipy.org/install.html
  519. #endif
  520. """
  521. cppmacros["F2PY_THREAD_LOCAL_DECL"] = """\
  522. #ifndef F2PY_THREAD_LOCAL_DECL
  523. #if defined(_MSC_VER) \\
  524. || defined(_WIN32) || defined(_WIN64) \\
  525. || defined(__MINGW32__) || defined(__MINGW64__)
  526. #define F2PY_THREAD_LOCAL_DECL __declspec(thread)
  527. #elif defined(__STDC_VERSION__) \\
  528. && (__STDC_VERSION__ >= 201112L) \\
  529. && !defined(__STDC_NO_THREADS__) \\
  530. && (!defined(__GLIBC__) || __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 12))
  531. /* __STDC_NO_THREADS__ was first defined in a maintenance release of glibc 2.12,
  532. see https://lists.gnu.org/archive/html/commit-hurd/2012-07/msg00180.html,
  533. so `!defined(__STDC_NO_THREADS__)` may give false positive for the existence
  534. of `threads.h` when using an older release of glibc 2.12 */
  535. #include <threads.h>
  536. #define F2PY_THREAD_LOCAL_DECL thread_local
  537. #elif defined(__GNUC__) \\
  538. && (__GNUC__ > 4 || (__GNUC__ == 4 && (__GNUC_MINOR__ >= 4)))
  539. #define F2PY_THREAD_LOCAL_DECL __thread
  540. #endif
  541. #endif
  542. """
  543. ################# C functions ###############
  544. cfuncs['calcarrindex'] = """\
  545. static int calcarrindex(int *i,PyArrayObject *arr) {
  546. int k,ii = i[0];
  547. for (k=1; k < PyArray_NDIM(arr); k++)
  548. ii += (ii*(PyArray_DIM(arr,k) - 1)+i[k]); /* assuming contiguous arr */
  549. return ii;
  550. }"""
  551. cfuncs['calcarrindextr'] = """\
  552. static int calcarrindextr(int *i,PyArrayObject *arr) {
  553. int k,ii = i[PyArray_NDIM(arr)-1];
  554. for (k=1; k < PyArray_NDIM(arr); k++)
  555. ii += (ii*(PyArray_DIM(arr,PyArray_NDIM(arr)-k-1) - 1)+i[PyArray_NDIM(arr)-k-1]); /* assuming contiguous arr */
  556. return ii;
  557. }"""
  558. cfuncs['forcomb'] = """\
  559. static struct { int nd;npy_intp *d;int *i,*i_tr,tr; } forcombcache;
  560. static int initforcomb(npy_intp *dims,int nd,int tr) {
  561. int k;
  562. if (dims==NULL) return 0;
  563. if (nd<0) return 0;
  564. forcombcache.nd = nd;
  565. forcombcache.d = dims;
  566. forcombcache.tr = tr;
  567. if ((forcombcache.i = (int *)malloc(sizeof(int)*nd))==NULL) return 0;
  568. if ((forcombcache.i_tr = (int *)malloc(sizeof(int)*nd))==NULL) return 0;
  569. for (k=1;k<nd;k++) {
  570. forcombcache.i[k] = forcombcache.i_tr[nd-k-1] = 0;
  571. }
  572. forcombcache.i[0] = forcombcache.i_tr[nd-1] = -1;
  573. return 1;
  574. }
  575. static int *nextforcomb(void) {
  576. int j,*i,*i_tr,k;
  577. int nd=forcombcache.nd;
  578. if ((i=forcombcache.i) == NULL) return NULL;
  579. if ((i_tr=forcombcache.i_tr) == NULL) return NULL;
  580. if (forcombcache.d == NULL) return NULL;
  581. i[0]++;
  582. if (i[0]==forcombcache.d[0]) {
  583. j=1;
  584. while ((j<nd) && (i[j]==forcombcache.d[j]-1)) j++;
  585. if (j==nd) {
  586. free(i);
  587. free(i_tr);
  588. return NULL;
  589. }
  590. for (k=0;k<j;k++) i[k] = i_tr[nd-k-1] = 0;
  591. i[j]++;
  592. i_tr[nd-j-1]++;
  593. } else
  594. i_tr[nd-1]++;
  595. if (forcombcache.tr) return i_tr;
  596. return i;
  597. }"""
  598. needs['try_pyarr_from_string'] = ['STRINGCOPYN', 'PRINTPYOBJERR', 'string']
  599. cfuncs['try_pyarr_from_string'] = """\
  600. static int try_pyarr_from_string(PyObject *obj,const string str) {
  601. PyArrayObject *arr = NULL;
  602. if (PyArray_Check(obj) && (!((arr = (PyArrayObject *)obj) == NULL)))
  603. { STRINGCOPYN(PyArray_DATA(arr),str,PyArray_NBYTES(arr)); }
  604. return 1;
  605. capi_fail:
  606. PRINTPYOBJERR(obj);
  607. PyErr_SetString(#modulename#_error,\"try_pyarr_from_string failed\");
  608. return 0;
  609. }
  610. """
  611. needs['string_from_pyobj'] = ['string', 'STRINGMALLOC', 'STRINGCOPYN']
  612. cfuncs['string_from_pyobj'] = """\
  613. static int
  614. string_from_pyobj(string *str,int *len,const string inistr,PyObject *obj,const char *errmess)
  615. {
  616. PyArrayObject *arr = NULL;
  617. PyObject *tmp = NULL;
  618. #ifdef DEBUGCFUNCS
  619. fprintf(stderr,\"string_from_pyobj(str='%s',len=%d,inistr='%s',obj=%p)\\n\",(char*)str,*len,(char *)inistr,obj);
  620. #endif
  621. if (obj == Py_None) {
  622. if (*len == -1)
  623. *len = strlen(inistr); /* Will this cause problems? */
  624. STRINGMALLOC(*str,*len);
  625. STRINGCOPYN(*str,inistr,*len+1);
  626. return 1;
  627. }
  628. if (PyArray_Check(obj)) {
  629. if ((arr = (PyArrayObject *)obj) == NULL)
  630. goto capi_fail;
  631. if (!ISCONTIGUOUS(arr)) {
  632. PyErr_SetString(PyExc_ValueError,\"array object is non-contiguous.\");
  633. goto capi_fail;
  634. }
  635. if (*len == -1)
  636. *len = (PyArray_ITEMSIZE(arr))*PyArray_SIZE(arr);
  637. STRINGMALLOC(*str,*len);
  638. STRINGCOPYN(*str,PyArray_DATA(arr),*len+1);
  639. return 1;
  640. }
  641. if (PyBytes_Check(obj)) {
  642. tmp = obj;
  643. Py_INCREF(tmp);
  644. }
  645. else if (PyUnicode_Check(obj)) {
  646. tmp = PyUnicode_AsASCIIString(obj);
  647. }
  648. else {
  649. PyObject *tmp2;
  650. tmp2 = PyObject_Str(obj);
  651. if (tmp2) {
  652. tmp = PyUnicode_AsASCIIString(tmp2);
  653. Py_DECREF(tmp2);
  654. }
  655. else {
  656. tmp = NULL;
  657. }
  658. }
  659. if (tmp == NULL) goto capi_fail;
  660. if (*len == -1)
  661. *len = PyBytes_GET_SIZE(tmp);
  662. STRINGMALLOC(*str,*len);
  663. STRINGCOPYN(*str,PyBytes_AS_STRING(tmp),*len+1);
  664. Py_DECREF(tmp);
  665. return 1;
  666. capi_fail:
  667. Py_XDECREF(tmp);
  668. {
  669. PyObject* err = PyErr_Occurred();
  670. if (err == NULL) {
  671. err = #modulename#_error;
  672. }
  673. PyErr_SetString(err, errmess);
  674. }
  675. return 0;
  676. }
  677. """
  678. needs['char_from_pyobj'] = ['int_from_pyobj']
  679. cfuncs['char_from_pyobj'] = """\
  680. static int
  681. char_from_pyobj(char* v, PyObject *obj, const char *errmess) {
  682. int i = 0;
  683. if (int_from_pyobj(&i, obj, errmess)) {
  684. *v = (char)i;
  685. return 1;
  686. }
  687. return 0;
  688. }
  689. """
  690. needs['signed_char_from_pyobj'] = ['int_from_pyobj', 'signed_char']
  691. cfuncs['signed_char_from_pyobj'] = """\
  692. static int
  693. signed_char_from_pyobj(signed_char* v, PyObject *obj, const char *errmess) {
  694. int i = 0;
  695. if (int_from_pyobj(&i, obj, errmess)) {
  696. *v = (signed_char)i;
  697. return 1;
  698. }
  699. return 0;
  700. }
  701. """
  702. needs['short_from_pyobj'] = ['int_from_pyobj']
  703. cfuncs['short_from_pyobj'] = """\
  704. static int
  705. short_from_pyobj(short* v, PyObject *obj, const char *errmess) {
  706. int i = 0;
  707. if (int_from_pyobj(&i, obj, errmess)) {
  708. *v = (short)i;
  709. return 1;
  710. }
  711. return 0;
  712. }
  713. """
  714. cfuncs['int_from_pyobj'] = """\
  715. static int
  716. int_from_pyobj(int* v, PyObject *obj, const char *errmess)
  717. {
  718. PyObject* tmp = NULL;
  719. if (PyLong_Check(obj)) {
  720. *v = Npy__PyLong_AsInt(obj);
  721. return !(*v == -1 && PyErr_Occurred());
  722. }
  723. tmp = PyNumber_Long(obj);
  724. if (tmp) {
  725. *v = Npy__PyLong_AsInt(tmp);
  726. Py_DECREF(tmp);
  727. return !(*v == -1 && PyErr_Occurred());
  728. }
  729. if (PyComplex_Check(obj))
  730. tmp = PyObject_GetAttrString(obj,\"real\");
  731. else if (PyBytes_Check(obj) || PyUnicode_Check(obj))
  732. /*pass*/;
  733. else if (PySequence_Check(obj))
  734. tmp = PySequence_GetItem(obj, 0);
  735. if (tmp) {
  736. PyErr_Clear();
  737. if (int_from_pyobj(v, tmp, errmess)) {
  738. Py_DECREF(tmp);
  739. return 1;
  740. }
  741. Py_DECREF(tmp);
  742. }
  743. {
  744. PyObject* err = PyErr_Occurred();
  745. if (err == NULL) {
  746. err = #modulename#_error;
  747. }
  748. PyErr_SetString(err, errmess);
  749. }
  750. return 0;
  751. }
  752. """
  753. cfuncs['long_from_pyobj'] = """\
  754. static int
  755. long_from_pyobj(long* v, PyObject *obj, const char *errmess) {
  756. PyObject* tmp = NULL;
  757. if (PyLong_Check(obj)) {
  758. *v = PyLong_AsLong(obj);
  759. return !(*v == -1 && PyErr_Occurred());
  760. }
  761. tmp = PyNumber_Long(obj);
  762. if (tmp) {
  763. *v = PyLong_AsLong(tmp);
  764. Py_DECREF(tmp);
  765. return !(*v == -1 && PyErr_Occurred());
  766. }
  767. if (PyComplex_Check(obj))
  768. tmp = PyObject_GetAttrString(obj,\"real\");
  769. else if (PyBytes_Check(obj) || PyUnicode_Check(obj))
  770. /*pass*/;
  771. else if (PySequence_Check(obj))
  772. tmp = PySequence_GetItem(obj,0);
  773. if (tmp) {
  774. PyErr_Clear();
  775. if (long_from_pyobj(v, tmp, errmess)) {
  776. Py_DECREF(tmp);
  777. return 1;
  778. }
  779. Py_DECREF(tmp);
  780. }
  781. {
  782. PyObject* err = PyErr_Occurred();
  783. if (err == NULL) {
  784. err = #modulename#_error;
  785. }
  786. PyErr_SetString(err, errmess);
  787. }
  788. return 0;
  789. }
  790. """
  791. needs['long_long_from_pyobj'] = ['long_long']
  792. cfuncs['long_long_from_pyobj'] = """\
  793. static int
  794. long_long_from_pyobj(long_long* v, PyObject *obj, const char *errmess)
  795. {
  796. PyObject* tmp = NULL;
  797. if (PyLong_Check(obj)) {
  798. *v = PyLong_AsLongLong(obj);
  799. return !(*v == -1 && PyErr_Occurred());
  800. }
  801. tmp = PyNumber_Long(obj);
  802. if (tmp) {
  803. *v = PyLong_AsLongLong(tmp);
  804. Py_DECREF(tmp);
  805. return !(*v == -1 && PyErr_Occurred());
  806. }
  807. if (PyComplex_Check(obj))
  808. tmp = PyObject_GetAttrString(obj,\"real\");
  809. else if (PyBytes_Check(obj) || PyUnicode_Check(obj))
  810. /*pass*/;
  811. else if (PySequence_Check(obj))
  812. tmp = PySequence_GetItem(obj,0);
  813. if (tmp) {
  814. PyErr_Clear();
  815. if (long_long_from_pyobj(v, tmp, errmess)) {
  816. Py_DECREF(tmp);
  817. return 1;
  818. }
  819. Py_DECREF(tmp);
  820. }
  821. {
  822. PyObject* err = PyErr_Occurred();
  823. if (err == NULL) {
  824. err = #modulename#_error;
  825. }
  826. PyErr_SetString(err,errmess);
  827. }
  828. return 0;
  829. }
  830. """
  831. needs['long_double_from_pyobj'] = ['double_from_pyobj', 'long_double']
  832. cfuncs['long_double_from_pyobj'] = """\
  833. static int
  834. long_double_from_pyobj(long_double* v, PyObject *obj, const char *errmess)
  835. {
  836. double d=0;
  837. if (PyArray_CheckScalar(obj)){
  838. if PyArray_IsScalar(obj, LongDouble) {
  839. PyArray_ScalarAsCtype(obj, v);
  840. return 1;
  841. }
  842. else if (PyArray_Check(obj) && PyArray_TYPE(obj) == NPY_LONGDOUBLE) {
  843. (*v) = *((npy_longdouble *)PyArray_DATA(obj));
  844. return 1;
  845. }
  846. }
  847. if (double_from_pyobj(&d, obj, errmess)) {
  848. *v = (long_double)d;
  849. return 1;
  850. }
  851. return 0;
  852. }
  853. """
  854. cfuncs['double_from_pyobj'] = """\
  855. static int
  856. double_from_pyobj(double* v, PyObject *obj, const char *errmess)
  857. {
  858. PyObject* tmp = NULL;
  859. if (PyFloat_Check(obj)) {
  860. *v = PyFloat_AsDouble(obj);
  861. return !(*v == -1.0 && PyErr_Occurred());
  862. }
  863. tmp = PyNumber_Float(obj);
  864. if (tmp) {
  865. *v = PyFloat_AsDouble(tmp);
  866. Py_DECREF(tmp);
  867. return !(*v == -1.0 && PyErr_Occurred());
  868. }
  869. if (PyComplex_Check(obj))
  870. tmp = PyObject_GetAttrString(obj,\"real\");
  871. else if (PyBytes_Check(obj) || PyUnicode_Check(obj))
  872. /*pass*/;
  873. else if (PySequence_Check(obj))
  874. tmp = PySequence_GetItem(obj,0);
  875. if (tmp) {
  876. PyErr_Clear();
  877. if (double_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;}
  878. Py_DECREF(tmp);
  879. }
  880. {
  881. PyObject* err = PyErr_Occurred();
  882. if (err==NULL) err = #modulename#_error;
  883. PyErr_SetString(err,errmess);
  884. }
  885. return 0;
  886. }
  887. """
  888. needs['float_from_pyobj'] = ['double_from_pyobj']
  889. cfuncs['float_from_pyobj'] = """\
  890. static int
  891. float_from_pyobj(float* v, PyObject *obj, const char *errmess)
  892. {
  893. double d=0.0;
  894. if (double_from_pyobj(&d,obj,errmess)) {
  895. *v = (float)d;
  896. return 1;
  897. }
  898. return 0;
  899. }
  900. """
  901. needs['complex_long_double_from_pyobj'] = ['complex_long_double', 'long_double',
  902. 'complex_double_from_pyobj']
  903. cfuncs['complex_long_double_from_pyobj'] = """\
  904. static int
  905. complex_long_double_from_pyobj(complex_long_double* v, PyObject *obj, const char *errmess)
  906. {
  907. complex_double cd = {0.0,0.0};
  908. if (PyArray_CheckScalar(obj)){
  909. if PyArray_IsScalar(obj, CLongDouble) {
  910. PyArray_ScalarAsCtype(obj, v);
  911. return 1;
  912. }
  913. else if (PyArray_Check(obj) && PyArray_TYPE(obj)==NPY_CLONGDOUBLE) {
  914. (*v).r = ((npy_clongdouble *)PyArray_DATA(obj))->real;
  915. (*v).i = ((npy_clongdouble *)PyArray_DATA(obj))->imag;
  916. return 1;
  917. }
  918. }
  919. if (complex_double_from_pyobj(&cd,obj,errmess)) {
  920. (*v).r = (long_double)cd.r;
  921. (*v).i = (long_double)cd.i;
  922. return 1;
  923. }
  924. return 0;
  925. }
  926. """
  927. needs['complex_double_from_pyobj'] = ['complex_double']
  928. cfuncs['complex_double_from_pyobj'] = """\
  929. static int
  930. complex_double_from_pyobj(complex_double* v, PyObject *obj, const char *errmess) {
  931. Py_complex c;
  932. if (PyComplex_Check(obj)) {
  933. c = PyComplex_AsCComplex(obj);
  934. (*v).r = c.real;
  935. (*v).i = c.imag;
  936. return 1;
  937. }
  938. if (PyArray_IsScalar(obj, ComplexFloating)) {
  939. if (PyArray_IsScalar(obj, CFloat)) {
  940. npy_cfloat new;
  941. PyArray_ScalarAsCtype(obj, &new);
  942. (*v).r = (double)new.real;
  943. (*v).i = (double)new.imag;
  944. }
  945. else if (PyArray_IsScalar(obj, CLongDouble)) {
  946. npy_clongdouble new;
  947. PyArray_ScalarAsCtype(obj, &new);
  948. (*v).r = (double)new.real;
  949. (*v).i = (double)new.imag;
  950. }
  951. else { /* if (PyArray_IsScalar(obj, CDouble)) */
  952. PyArray_ScalarAsCtype(obj, v);
  953. }
  954. return 1;
  955. }
  956. if (PyArray_CheckScalar(obj)) { /* 0-dim array or still array scalar */
  957. PyObject *arr;
  958. if (PyArray_Check(obj)) {
  959. arr = PyArray_Cast((PyArrayObject *)obj, NPY_CDOUBLE);
  960. }
  961. else {
  962. arr = PyArray_FromScalar(obj, PyArray_DescrFromType(NPY_CDOUBLE));
  963. }
  964. if (arr == NULL) {
  965. return 0;
  966. }
  967. (*v).r = ((npy_cdouble *)PyArray_DATA(arr))->real;
  968. (*v).i = ((npy_cdouble *)PyArray_DATA(arr))->imag;
  969. Py_DECREF(arr);
  970. return 1;
  971. }
  972. /* Python does not provide PyNumber_Complex function :-( */
  973. (*v).i = 0.0;
  974. if (PyFloat_Check(obj)) {
  975. (*v).r = PyFloat_AsDouble(obj);
  976. return !((*v).r == -1.0 && PyErr_Occurred());
  977. }
  978. if (PyLong_Check(obj)) {
  979. (*v).r = PyLong_AsDouble(obj);
  980. return !((*v).r == -1.0 && PyErr_Occurred());
  981. }
  982. if (PySequence_Check(obj) && !(PyBytes_Check(obj) || PyUnicode_Check(obj))) {
  983. PyObject *tmp = PySequence_GetItem(obj,0);
  984. if (tmp) {
  985. if (complex_double_from_pyobj(v,tmp,errmess)) {
  986. Py_DECREF(tmp);
  987. return 1;
  988. }
  989. Py_DECREF(tmp);
  990. }
  991. }
  992. {
  993. PyObject* err = PyErr_Occurred();
  994. if (err==NULL)
  995. err = PyExc_TypeError;
  996. PyErr_SetString(err,errmess);
  997. }
  998. return 0;
  999. }
  1000. """
  1001. needs['complex_float_from_pyobj'] = [
  1002. 'complex_float', 'complex_double_from_pyobj']
  1003. cfuncs['complex_float_from_pyobj'] = """\
  1004. static int
  1005. complex_float_from_pyobj(complex_float* v,PyObject *obj,const char *errmess)
  1006. {
  1007. complex_double cd={0.0,0.0};
  1008. if (complex_double_from_pyobj(&cd,obj,errmess)) {
  1009. (*v).r = (float)cd.r;
  1010. (*v).i = (float)cd.i;
  1011. return 1;
  1012. }
  1013. return 0;
  1014. }
  1015. """
  1016. needs['try_pyarr_from_char'] = ['pyobj_from_char1', 'TRYPYARRAYTEMPLATE']
  1017. cfuncs[
  1018. 'try_pyarr_from_char'] = 'static int try_pyarr_from_char(PyObject* obj,char* v) {\n TRYPYARRAYTEMPLATE(char,\'c\');\n}\n'
  1019. needs['try_pyarr_from_signed_char'] = ['TRYPYARRAYTEMPLATE', 'unsigned_char']
  1020. cfuncs[
  1021. 'try_pyarr_from_unsigned_char'] = 'static int try_pyarr_from_unsigned_char(PyObject* obj,unsigned_char* v) {\n TRYPYARRAYTEMPLATE(unsigned_char,\'b\');\n}\n'
  1022. needs['try_pyarr_from_signed_char'] = ['TRYPYARRAYTEMPLATE', 'signed_char']
  1023. cfuncs[
  1024. 'try_pyarr_from_signed_char'] = 'static int try_pyarr_from_signed_char(PyObject* obj,signed_char* v) {\n TRYPYARRAYTEMPLATE(signed_char,\'1\');\n}\n'
  1025. needs['try_pyarr_from_short'] = ['pyobj_from_short1', 'TRYPYARRAYTEMPLATE']
  1026. cfuncs[
  1027. 'try_pyarr_from_short'] = 'static int try_pyarr_from_short(PyObject* obj,short* v) {\n TRYPYARRAYTEMPLATE(short,\'s\');\n}\n'
  1028. needs['try_pyarr_from_int'] = ['pyobj_from_int1', 'TRYPYARRAYTEMPLATE']
  1029. cfuncs[
  1030. 'try_pyarr_from_int'] = 'static int try_pyarr_from_int(PyObject* obj,int* v) {\n TRYPYARRAYTEMPLATE(int,\'i\');\n}\n'
  1031. needs['try_pyarr_from_long'] = ['pyobj_from_long1', 'TRYPYARRAYTEMPLATE']
  1032. cfuncs[
  1033. 'try_pyarr_from_long'] = 'static int try_pyarr_from_long(PyObject* obj,long* v) {\n TRYPYARRAYTEMPLATE(long,\'l\');\n}\n'
  1034. needs['try_pyarr_from_long_long'] = [
  1035. 'pyobj_from_long_long1', 'TRYPYARRAYTEMPLATE', 'long_long']
  1036. cfuncs[
  1037. 'try_pyarr_from_long_long'] = 'static int try_pyarr_from_long_long(PyObject* obj,long_long* v) {\n TRYPYARRAYTEMPLATE(long_long,\'L\');\n}\n'
  1038. needs['try_pyarr_from_float'] = ['pyobj_from_float1', 'TRYPYARRAYTEMPLATE']
  1039. cfuncs[
  1040. 'try_pyarr_from_float'] = 'static int try_pyarr_from_float(PyObject* obj,float* v) {\n TRYPYARRAYTEMPLATE(float,\'f\');\n}\n'
  1041. needs['try_pyarr_from_double'] = ['pyobj_from_double1', 'TRYPYARRAYTEMPLATE']
  1042. cfuncs[
  1043. 'try_pyarr_from_double'] = 'static int try_pyarr_from_double(PyObject* obj,double* v) {\n TRYPYARRAYTEMPLATE(double,\'d\');\n}\n'
  1044. needs['try_pyarr_from_complex_float'] = [
  1045. 'pyobj_from_complex_float1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_float']
  1046. cfuncs[
  1047. 'try_pyarr_from_complex_float'] = 'static int try_pyarr_from_complex_float(PyObject* obj,complex_float* v) {\n TRYCOMPLEXPYARRAYTEMPLATE(float,\'F\');\n}\n'
  1048. needs['try_pyarr_from_complex_double'] = [
  1049. 'pyobj_from_complex_double1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_double']
  1050. cfuncs[
  1051. 'try_pyarr_from_complex_double'] = 'static int try_pyarr_from_complex_double(PyObject* obj,complex_double* v) {\n TRYCOMPLEXPYARRAYTEMPLATE(double,\'D\');\n}\n'
  1052. needs['create_cb_arglist'] = ['CFUNCSMESS', 'PRINTPYOBJERR', 'MINMAX']
  1053. # create the list of arguments to be used when calling back to python
  1054. cfuncs['create_cb_arglist'] = """\
  1055. static int
  1056. create_cb_arglist(PyObject* fun, PyTupleObject* xa , const int maxnofargs,
  1057. const int nofoptargs, int *nofargs, PyTupleObject **args,
  1058. const char *errmess)
  1059. {
  1060. PyObject *tmp = NULL;
  1061. PyObject *tmp_fun = NULL;
  1062. Py_ssize_t tot, opt, ext, siz, i, di = 0;
  1063. CFUNCSMESS(\"create_cb_arglist\\n\");
  1064. tot=opt=ext=siz=0;
  1065. /* Get the total number of arguments */
  1066. if (PyFunction_Check(fun)) {
  1067. tmp_fun = fun;
  1068. Py_INCREF(tmp_fun);
  1069. }
  1070. else {
  1071. di = 1;
  1072. if (PyObject_HasAttrString(fun,\"im_func\")) {
  1073. tmp_fun = PyObject_GetAttrString(fun,\"im_func\");
  1074. }
  1075. else if (PyObject_HasAttrString(fun,\"__call__\")) {
  1076. tmp = PyObject_GetAttrString(fun,\"__call__\");
  1077. if (PyObject_HasAttrString(tmp,\"im_func\"))
  1078. tmp_fun = PyObject_GetAttrString(tmp,\"im_func\");
  1079. else {
  1080. tmp_fun = fun; /* built-in function */
  1081. Py_INCREF(tmp_fun);
  1082. tot = maxnofargs;
  1083. if (PyCFunction_Check(fun)) {
  1084. /* In case the function has a co_argcount (like on PyPy) */
  1085. di = 0;
  1086. }
  1087. if (xa != NULL)
  1088. tot += PyTuple_Size((PyObject *)xa);
  1089. }
  1090. Py_XDECREF(tmp);
  1091. }
  1092. else if (PyFortran_Check(fun) || PyFortran_Check1(fun)) {
  1093. tot = maxnofargs;
  1094. if (xa != NULL)
  1095. tot += PyTuple_Size((PyObject *)xa);
  1096. tmp_fun = fun;
  1097. Py_INCREF(tmp_fun);
  1098. }
  1099. else if (F2PyCapsule_Check(fun)) {
  1100. tot = maxnofargs;
  1101. if (xa != NULL)
  1102. ext = PyTuple_Size((PyObject *)xa);
  1103. if(ext>0) {
  1104. fprintf(stderr,\"extra arguments tuple cannot be used with CObject call-back\\n\");
  1105. goto capi_fail;
  1106. }
  1107. tmp_fun = fun;
  1108. Py_INCREF(tmp_fun);
  1109. }
  1110. }
  1111. if (tmp_fun == NULL) {
  1112. fprintf(stderr,
  1113. \"Call-back argument must be function|instance|instance.__call__|f2py-function \"
  1114. \"but got %s.\\n\",
  1115. ((fun == NULL) ? \"NULL\" : Py_TYPE(fun)->tp_name));
  1116. goto capi_fail;
  1117. }
  1118. if (PyObject_HasAttrString(tmp_fun,\"__code__\")) {
  1119. if (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,\"__code__\"),\"co_argcount\")) {
  1120. PyObject *tmp_argcount = PyObject_GetAttrString(tmp,\"co_argcount\");
  1121. Py_DECREF(tmp);
  1122. if (tmp_argcount == NULL) {
  1123. goto capi_fail;
  1124. }
  1125. tot = PyLong_AsSsize_t(tmp_argcount) - di;
  1126. Py_DECREF(tmp_argcount);
  1127. }
  1128. }
  1129. /* Get the number of optional arguments */
  1130. if (PyObject_HasAttrString(tmp_fun,\"__defaults__\")) {
  1131. if (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,\"__defaults__\")))
  1132. opt = PyTuple_Size(tmp);
  1133. Py_XDECREF(tmp);
  1134. }
  1135. /* Get the number of extra arguments */
  1136. if (xa != NULL)
  1137. ext = PyTuple_Size((PyObject *)xa);
  1138. /* Calculate the size of call-backs argument list */
  1139. siz = MIN(maxnofargs+ext,tot);
  1140. *nofargs = MAX(0,siz-ext);
  1141. #ifdef DEBUGCFUNCS
  1142. fprintf(stderr,
  1143. \"debug-capi:create_cb_arglist:maxnofargs(-nofoptargs),\"
  1144. \"tot,opt,ext,siz,nofargs = %d(-%d), %zd, %zd, %zd, %zd, %d\\n\",
  1145. maxnofargs, nofoptargs, tot, opt, ext, siz, *nofargs);
  1146. #endif
  1147. if (siz < tot-opt) {
  1148. fprintf(stderr,
  1149. \"create_cb_arglist: Failed to build argument list \"
  1150. \"(siz) with enough arguments (tot-opt) required by \"
  1151. \"user-supplied function (siz,tot,opt=%zd, %zd, %zd).\\n\",
  1152. siz, tot, opt);
  1153. goto capi_fail;
  1154. }
  1155. /* Initialize argument list */
  1156. *args = (PyTupleObject *)PyTuple_New(siz);
  1157. for (i=0;i<*nofargs;i++) {
  1158. Py_INCREF(Py_None);
  1159. PyTuple_SET_ITEM((PyObject *)(*args),i,Py_None);
  1160. }
  1161. if (xa != NULL)
  1162. for (i=(*nofargs);i<siz;i++) {
  1163. tmp = PyTuple_GetItem((PyObject *)xa,i-(*nofargs));
  1164. Py_INCREF(tmp);
  1165. PyTuple_SET_ITEM(*args,i,tmp);
  1166. }
  1167. CFUNCSMESS(\"create_cb_arglist-end\\n\");
  1168. Py_DECREF(tmp_fun);
  1169. return 1;
  1170. capi_fail:
  1171. if (PyErr_Occurred() == NULL)
  1172. PyErr_SetString(#modulename#_error, errmess);
  1173. Py_XDECREF(tmp_fun);
  1174. return 0;
  1175. }
  1176. """
  1177. def buildcfuncs():
  1178. from .capi_maps import c2capi_map
  1179. for k in c2capi_map.keys():
  1180. m = 'pyarr_from_p_%s1' % k
  1181. cppmacros[
  1182. m] = '#define %s(v) (PyArray_SimpleNewFromData(0,NULL,%s,(char *)v))' % (m, c2capi_map[k])
  1183. k = 'string'
  1184. m = 'pyarr_from_p_%s1' % k
  1185. # NPY_CHAR compatibility, NPY_STRING with itemsize 1
  1186. cppmacros[
  1187. m] = '#define %s(v,dims) (PyArray_New(&PyArray_Type, 1, dims, NPY_STRING, NULL, v, 1, NPY_ARRAY_CARRAY, NULL))' % (m)
  1188. ############ Auxiliary functions for sorting needs ###################
  1189. def append_needs(need, flag=1):
  1190. # This function modifies the contents of the global `outneeds` dict.
  1191. if isinstance(need, list):
  1192. for n in need:
  1193. append_needs(n, flag)
  1194. elif isinstance(need, str):
  1195. if not need:
  1196. return
  1197. if need in includes0:
  1198. n = 'includes0'
  1199. elif need in includes:
  1200. n = 'includes'
  1201. elif need in typedefs:
  1202. n = 'typedefs'
  1203. elif need in typedefs_generated:
  1204. n = 'typedefs_generated'
  1205. elif need in cppmacros:
  1206. n = 'cppmacros'
  1207. elif need in cfuncs:
  1208. n = 'cfuncs'
  1209. elif need in callbacks:
  1210. n = 'callbacks'
  1211. elif need in f90modhooks:
  1212. n = 'f90modhooks'
  1213. elif need in commonhooks:
  1214. n = 'commonhooks'
  1215. else:
  1216. errmess('append_needs: unknown need %s\n' % (repr(need)))
  1217. return
  1218. if need in outneeds[n]:
  1219. return
  1220. if flag:
  1221. tmp = {}
  1222. if need in needs:
  1223. for nn in needs[need]:
  1224. t = append_needs(nn, 0)
  1225. if isinstance(t, dict):
  1226. for nnn in t.keys():
  1227. if nnn in tmp:
  1228. tmp[nnn] = tmp[nnn] + t[nnn]
  1229. else:
  1230. tmp[nnn] = t[nnn]
  1231. for nn in tmp.keys():
  1232. for nnn in tmp[nn]:
  1233. if nnn not in outneeds[nn]:
  1234. outneeds[nn] = [nnn] + outneeds[nn]
  1235. outneeds[n].append(need)
  1236. else:
  1237. tmp = {}
  1238. if need in needs:
  1239. for nn in needs[need]:
  1240. t = append_needs(nn, flag)
  1241. if isinstance(t, dict):
  1242. for nnn in t.keys():
  1243. if nnn in tmp:
  1244. tmp[nnn] = t[nnn] + tmp[nnn]
  1245. else:
  1246. tmp[nnn] = t[nnn]
  1247. if n not in tmp:
  1248. tmp[n] = []
  1249. tmp[n].append(need)
  1250. return tmp
  1251. else:
  1252. errmess('append_needs: expected list or string but got :%s\n' %
  1253. (repr(need)))
  1254. def get_needs():
  1255. # This function modifies the contents of the global `outneeds` dict.
  1256. res = {}
  1257. for n in outneeds.keys():
  1258. out = []
  1259. saveout = copy.copy(outneeds[n])
  1260. while len(outneeds[n]) > 0:
  1261. if outneeds[n][0] not in needs:
  1262. out.append(outneeds[n][0])
  1263. del outneeds[n][0]
  1264. else:
  1265. flag = 0
  1266. for k in outneeds[n][1:]:
  1267. if k in needs[outneeds[n][0]]:
  1268. flag = 1
  1269. break
  1270. if flag:
  1271. outneeds[n] = outneeds[n][1:] + [outneeds[n][0]]
  1272. else:
  1273. out.append(outneeds[n][0])
  1274. del outneeds[n][0]
  1275. if saveout and (0 not in map(lambda x, y: x == y, saveout, outneeds[n])) \
  1276. and outneeds[n] != []:
  1277. print(n, saveout)
  1278. errmess(
  1279. 'get_needs: no progress in sorting needs, probably circular dependence, skipping.\n')
  1280. out = out + saveout
  1281. break
  1282. saveout = copy.copy(outneeds[n])
  1283. if out == []:
  1284. out = [n]
  1285. res[n] = out
  1286. return res