Submit 'int' and 'string' arrays using ctypes (Python->C++) -
i've simple working program submits int (num_piezasin example) python function c++ function.
foo.cpp
#include <iostream> class foo{ public: void bar(int number){ printf("number is: %d\n", number); } }; extern "c" { foo* foo_new(){ return new foo(); } void foo_bar(foo* foo, int number){ foo->bar(number); } } foowrapper.py
from ctypes import cdll lib = cdll.loadlibrary('./libfoo.so') class foo(object): def __init__(self): self.obj = lib.foo_new() def bar(self, num_piezas): lib.foo_bar(self.obj, num_piezas) num_piezas = 5 f = foo() f.bar(num_piezas) the thing want send int array , char array along number. tried:
foo.cpp
#include <iostream> #include <string.h> class foo{ public: void bar(int number, int piezas[3], char prioridades[3][20]){ printf("number is: %d\n", number); for(int i=0;i<3;i++) { printf("%d", piezas[i]); } for(int q=0;q<3;q++) { printf("%s ", prioridades[q]); } } }; extern "c" { foo* foo_new(){ return new foo(); } void foo_bar(foo* foo, int number, int piezas[3], char prioridades[3][20]){ foo->bar(number, piezas, prioridades); } } foowrapper.py
from ctypes import cdll lib = cdll.loadlibrary('./libfoo.so') class foo(object): def __init__(self): self.obj = lib.foo_new() def bar(self, num_piezas, piezas, prioridades): lib.foo_bar(self.obj, num_piezas, piezas, prioridades) piezas = [1, 2, 3] prioridades = ['normal', 'baja', 'primera pieza'] num_piezas = 5 f = foo() f.bar(num_piezas, piezas, prioridades) the c++ file compiles correctly, when try execute python function (python foowrapper.py) error message shows up:
traceback (most recent call last): file "foowrapper.py", line 15, in <module> f.bar(num_piezas, piezas, prioridades) file "foowrapper.py", line 9, in bar lib.foo_bar(self.obj, num_piezas, piezas, prioridades) ctypes.argumenterror: argument 3: <type 'exceptions.typeerror'>: don't know how convert parameter 3
what i'm doing wrong? need else pass int , string arrays parameters? in advance.
you can away modification :
from ctypes import c_int, c_char ... # create 3-int array piezas = (c_int*3)() piezas[0] = 1 piezas[1] = 2 piezas[2] = 3 # create 3-(20-char array) array prio = ((c_char*20)*3)() prio[0].value = "normal" prio[1].value = "baja" prio[2].value = "primera pieza" but since you're dealing char arrays in c++ side part, advise change function defintion : void bar( int num, char* piezas, int len_piezas, char** prio , int len_prio_elem, int prio);. longer, have control length of input arrays if want avoid buffer overflows.
Comments
Post a Comment