Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- articles:
- Interfacing Python with C using ctypes
- http://blog.prashanthellina.com/interfacing-python-with-c-using-ctypes.html
- Shared objects for the object disoriented!
- https://www.ibm.com/developerworks/library/l-shobj/
- ctypes — A foreign function library for Python
- https://docs.python.org/3/library/ctypes.html
- Interfacing Python and C using Ctypes
- http://indico.ictp.it/event/7657/session/4/contribution/19/material/1/0.pdf
- */
- /*
- build shared library:
- gcc -fPIC -c test.c
- ld -shared -soname libtest.so.1 -o libtest.so.1.0 -lc test.o
- file testc.py
- # begin
- from ctypes import *
- lib = cdll.LoadLibrary('./libtest.so.1.0')
- print(lib.addi(1, 2))
- a = c_float(1.7)
- b = c_float(1.8)
- print("a: %.5f b: %.5f" % (a.value,b.value))
- lib.addf.restype=c_float
- print("%.5f" % lib.addf(c_float(1.7),c_float(1.8)))
- print("a before (1): %.5f" % a.value)
- lib.addfbr(byref(a))
- print("a after (1): %.5f" % a.value)
- f_array = (c_float * 16)(*range(16))
- print(sizeof(f_array))
- f_array[0] = 300.1
- f_array[1] = 300.2
- lib.addfbrarr.restype=c_bool
- retval = c_bool()
- print("before (2): %.5f %.5f" % (f_array[0],f_array[1]))
- retval = lib.addfbrarr(byref(f_array),16)
- if retval:
- print("ERROR: addfbrarr")
- else:
- print("after (2): %.5f %.5f" % (f_array[0],f_array[1]))
- # end
- run:
- python3 testc.py
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- void _init()
- {
- printf("init\n");
- }
- void _fini()
- {
- printf("fini\n");
- }
- int addi(int a, int b)
- {
- return a + b;
- }
- float addf(float a, float b)
- {
- return a + b;
- }
- void addfbr(float* a)
- {
- *a = *a + 1.0f;
- }
- bool addfbrarr(float* a, unsigned int numOfE)
- {
- printf("sizeof float %zu\n",sizeof(float));
- printf("sizeof float* %zu\n",sizeof(float*));
- float* tmp;
- unsigned int offset = 0;
- if(offset<numOfE)
- {
- tmp = a + offset;
- printf("address of tmp: %p\n", (void*) tmp);
- *tmp = *tmp + 1.0f;
- }
- else return 1;
- offset++;
- //tmp += 1; adds sizeof(float)
- if(offset<numOfE)
- {
- tmp = a + offset;
- printf("address of tmp: %p\n", (void*) tmp);
- *tmp = *tmp + 1.0f;
- }
- else return 1;
- return 0;
- }
- /*
- output:
- init
- 3
- a: 1.70000 b: 1.80000
- 3.50000
- a before (1): 1.70000
- a after (1): 2.70000
- 64
- before (2): 300.10001 300.20001
- sizeof float 4
- sizeof float* 8
- address of tmp: 0x7f93fa8fc6f0
- address of tmp: 0x7f93fa8fc6f4
- after (2): 301.10001 301.20001
- fini
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement