我正在嘗試使用 ctypes 與 c 代碼互動。我正在嘗試通過參考 c 來傳遞 obj,并且我正在使用 numpy 的 ndpointer 函式來傳遞給該函式。
我的 C 代碼:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void sum(int *a, int *b, int *c, size_t m) {
int ix;
for (ix=0; ix<m; ix ) {
printf("%d: (%d,%d)\n",ix, a[ix], b[ix]);
c[ix] = a[ix] b[ix];
}
}
將其編譯為 ubuntu 20.04 上的共享庫,使用
gcc -Wall -fPIC -shared -pedantic -shared test.c -o test.so
我的python包裝器是:
import ctypes
from numpy.ctypeslib import ndpointer
import numpy as np
add = ctypes.CDLL('testing_ctypes/test.so').sum
add.argtypes = [ndpointer(dtype=np.int64, ndim=1, flags="aligned, c_contiguous"), ndpointer(dtype=np.int64, ndim=1, flags="aligned, c_contiguous"), ndpointer(dtype=np.int64, ndim=1,flags="aligned, c_contiguous"), ctypes.c_size_t]
add.restype = None
def test_add(a, b):
c = np.array([0,0,0], dtype=np.int64)
add(a,b,c,5)
return c
op = test_add(np.array([1, 10, 5], np.int64), np.array([5, 4, 6], np.int64))
當我運行此代碼時,我得到輸出:
0: (1,5)
1: (0,0)
2: (10,4)
3: (0,0)
4: (5,6)
為什么值不連續?我嘗試了numpy 參考中給出的不同標志, 但它們都對輸出沒有任何影響。我很困惑為什么這會是輸出。任何幫助表示贊賞!
uj5u.com熱心網友回復:
您的 C 函式接受int *引數,但您np.array使用的是 64 位整數。在 C 中,int是 4 個位元組(32 位)。試試np.int32。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/426280.html
上一篇:兩條曲線之間的面積
