Я хочу иметь возможность передавать структуру в какой-нибудь c-код и использую ctypes.structure. У меня есть простой рабочий пример, который принимает входной массив, возводит элементы в квадрат и выводит в виде массива. Однако у меня возникли проблемы с помещением этого в класс Python для создания процедуры-оболочки.
Буду очень признателен за любую помощь!
Роб< /p>
Простой c-код test.c:
%%%%%%%%%%%%%%%%%
test.c
struct DATA;
typedef struct DATA
{
int n;
double *ina;
double *outa;
} DATA;
void square_array2(DATA *data)
{
int i;
for (i=0; in; i++)
{
data->outa = data->ina*data->ina;
}
}
Я компилирую это с помощью
gcc -shared -fPIC test.c -o test.so
В блокноте Jupyter у меня есть....
import importlib
import numpy as np
import ctypes
from ctypes import CDLL, POINTER
from ctypes import c_size_t, c_double
from wurlitzer import pipes, STDOUT
%reload_ext wurlitzer
testlib = CDLL('test.so')
n=5
ina = np.linspace(1.0,5.0,n)
outa = np.zeros(n,np.float64)
class Data(ctypes.Structure):
_fields_ = [("n", ctypes.c_int),
("ina", ctypes.POINTER(ctypes.c_double)),
("outa", ctypes.POINTER(ctypes.c_double))]
data = Data(n,np.ctypeslib.as_ctypes(ina),np.ctypeslib.as_ctypes(outa))
print("initial array",ina)
testlib.square_array2.restype = None
testlib.square_array2(ctypes.byref(data))
print("final array",outa)
Все это отлично работает из блокнота Jupyter.....
Часть, которая не работает, — это размещение этого
в оболочку класса Python..... вот моя попытка обертки, которая не работает.
import ctypes
from ctypes import CDLL, POINTER
from ctypes import c_size_t, c_double, c_int
from io import StringIO
from wurlitzer import pipes, STDOUT
class Data(ctypes.Structure):
_fields_ = [("n", ctypes.c_int),
("ina", ctypes.POINTER(ctypes.c_double)),
("outa", ctypes.POINTER(ctypes.c_double))]
class testClib(Data): #attempting to inherit the Data class.
def __init__(self):
# load the library
self.lib = CDLL("test.so")
def square_array2(self,ina,outa):
n, = ina.shape
# !!! the line that doesn't work....
data = Data(n,np.ctypeslib.as_ctypes(ina),np.ctypeslib.as_ctypes(outa))
out = StringIO()
with pipes(stdout=out, stderr=STDOUT):
self.lib.square_array2.restype = None
self.lib.square_array2(ctypes.byref(data))
stdout = out.getvalue()
print(stdout)
print(ina)
print(outa)
Подробнее здесь: https://stackoverflow.com/questions/791 ... -in-python
Упаковка ctypes ctypes. Структура внутри класса в Python ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Python ctypes и np.array.ctypes.data_as неожиданное поведение при нарезке
Anonymous » » в форуме Python - 0 Ответы
- 41 Просмотры
-
Последнее сообщение Anonymous
-