ctypes - Python -Why cannot change the value in the C callback function? -


i try using python ctype call c library (.so) , , c library have callback function. c source code:


int showhelloword(int *result) {     *result = 1025;     return 55; }  void bsp_show(int time,int (*callback)(int *result)) {     int ret = 44;     int boo = 4;     while(time > 0){         --time;         if(time == 0){             if(callback) {                 printf("boo %d\n",boo);      // expect boo=4                 ret = callback(&boo);                 printf("outfunc=%d\n",boo);  // expect outfunc=1025                 printf("ret=%d\n",ret);      // expect ret=55             }                     callback = 0;         }         sleep(1);     } }  void main(){     bsp_show( 2, &showhelloword); } 

the print rseult :

boo=4 outfunc=1025 ret=55 

and seem okay.

makefile source :

gcc -c -fpic -wno-format-security -g main.c gcc -shared -o libcall.so main.o gcc main.o -o callback -ldl -lpthread -lrt  

then, try using python ctype call "bsp_show" function , callback function. python source :

python version : 2.6.6


import sys import os import time ctypes import * import struct queue import *  class callback_api(object):      def __init__(self):         cdll("/usr/lib64/librt.so",mode=rtld_global)         path = "/root/workspace/callback/libcall.so"  `c library path`         self.dll = cdll.loadlibrary(path)      def bsp_show(self,sec, cb_func):         self.dll.bsp_show.restype = none         self.dll.bsp_show.argtypes = [c_int, qa_cb_prototype]         self.dll.bsp_show(c_int(sec),cb_func)       def qa_callback(result):         result = 1025 #it should change value. result not....         return 88  qa_cb_prototype = cfunctype( c_int, pointer(c_int)) qa_cache_cb_func = qa_cb_prototype(qa_callback)  if __name__ == '__main__':     api = callback_api()     api.bsp_show(2,qa_cache_cb_func) `got callback` 

the print result is.

cb=4 outfunc=4 <---i expect should 1025,but not!  ret=88 <---return value have been change python callback. 

have know python ctype limitation or use wrong method? thanks!

the = operator reassigns variable in python. in other words, change variable means.

you need change variable pointing to. since it's ctypes pointer, need index 0 this.

     def qa_callback(result):         result[0] = 1025         return 88 

note [0] after result.

see also: https://docs.python.org/2/library/ctypes.html#pointers


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -