質問編集履歴
1
コード、コンパイル方法の追加
test
CHANGED
File without changes
|
test
CHANGED
@@ -9,3 +9,129 @@
|
|
9
9
|
参考にしたサイトのURLはこちらです。
|
10
10
|
|
11
11
|
https://qiita.com/motacapla/items/01de7d59cacb3f96caaf
|
12
|
+
|
13
|
+
|
14
|
+
|
15
|
+
cのコード 引数の行列の全要素にnを足すもの
|
16
|
+
|
17
|
+
```
|
18
|
+
|
19
|
+
#include <stdio.h>
|
20
|
+
|
21
|
+
|
22
|
+
|
23
|
+
void add_matrix(double **matrix, int row, int col, int n) {
|
24
|
+
|
25
|
+
int i, j;
|
26
|
+
|
27
|
+
for(i=0; i<row; i++){
|
28
|
+
|
29
|
+
for(j=0; j<col; j++){
|
30
|
+
|
31
|
+
matrix[i][j] = matrix[i][j] + n;
|
32
|
+
|
33
|
+
}
|
34
|
+
|
35
|
+
}
|
36
|
+
|
37
|
+
}
|
38
|
+
|
39
|
+
|
40
|
+
|
41
|
+
```
|
42
|
+
|
43
|
+
|
44
|
+
|
45
|
+
コンパイル方法
|
46
|
+
|
47
|
+
```
|
48
|
+
|
49
|
+
gcc -cpp -fPIC -shared libadd.c -lm -o libadd.so -O3
|
50
|
+
|
51
|
+
```
|
52
|
+
|
53
|
+
|
54
|
+
|
55
|
+
|
56
|
+
|
57
|
+
|
58
|
+
|
59
|
+
pythonコード
|
60
|
+
|
61
|
+
```
|
62
|
+
|
63
|
+
from ctypes import *
|
64
|
+
|
65
|
+
import ctypes.util
|
66
|
+
|
67
|
+
from numpy.ctypeslib import ndpointer
|
68
|
+
|
69
|
+
import numpy as np
|
70
|
+
|
71
|
+
from numpy.random import *
|
72
|
+
|
73
|
+
|
74
|
+
|
75
|
+
#さっきつくったlibadd.soファイルを指定
|
76
|
+
|
77
|
+
lib = np.ctypeslib.load_library("libadd.so",".")
|
78
|
+
|
79
|
+
|
80
|
+
|
81
|
+
#適当につくります
|
82
|
+
|
83
|
+
row = 20
|
84
|
+
|
85
|
+
col = 5
|
86
|
+
|
87
|
+
n = 5
|
88
|
+
|
89
|
+
matrix = rand(row, col)
|
90
|
+
|
91
|
+
|
92
|
+
|
93
|
+
#doubleのポインタのポインタ型を用意
|
94
|
+
|
95
|
+
_DOUBLE_PP = ndpointer(dtype=np.uintp, ndim=1, flags='C')
|
96
|
+
|
97
|
+
#add_matrix()関数の引数の型を指定(ctypes)
|
98
|
+
|
99
|
+
lib.add_matrix.argtypes = [_DOUBLE_PP, c_int32, c_int32, c_int32]
|
100
|
+
|
101
|
+
#add_matrix()関数が返す値の型を指定(今回は返り値なし)
|
102
|
+
|
103
|
+
lib.add_matrix.restype = None
|
104
|
+
|
105
|
+
|
106
|
+
|
107
|
+
#おまじない
|
108
|
+
|
109
|
+
tp = np.uintp
|
110
|
+
|
111
|
+
mpp = (matrix.__array_interface__['data'][0] + np.arange(matrix.shape[0])*matrix.strides[0]).astype(tp)
|
112
|
+
|
113
|
+
|
114
|
+
|
115
|
+
#int型もctypeのc_int型へ変換して渡す
|
116
|
+
|
117
|
+
n = ctypes.c_int(n)
|
118
|
+
|
119
|
+
row = ctypes.c_int(row)
|
120
|
+
|
121
|
+
col = ctypes.c_int(col)
|
122
|
+
|
123
|
+
|
124
|
+
|
125
|
+
print("before:", matrix)
|
126
|
+
|
127
|
+
|
128
|
+
|
129
|
+
lib.add_matrix(mpp, row, col, n)
|
130
|
+
|
131
|
+
|
132
|
+
|
133
|
+
print("after:", matrix)
|
134
|
+
|
135
|
+
|
136
|
+
|
137
|
+
```
|