Created
November 11, 2011 23:02
-
-
Save yangle/1359591 to your computer and use it in GitHub Desktop.
ctypes examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // gcc -std=c99 -O3 -fPIC -shared -Wl,-soname,mylib -o mylib.so mylib.c | |
| #include <stdio.h> | |
| #include <complex.h> | |
| int build_hamiltonian(int i, double d, complex double *m) | |
| { | |
| m[0]=2.*I; | |
| return 0; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| from numpy.ctypeslib import ndpointer | |
| from ctypes import * | |
| class PointerWrapper(object): | |
| """Just like ndpointer, but accept None!""" | |
| def __init__(self,pointer): | |
| self.pointer=pointer | |
| def from_param(self,param): | |
| if param!=None: | |
| return self.pointer.from_param(param) | |
| else: | |
| return POINTER(c_double).from_param(None) | |
| mylib=CDLL('/tmp/mylib.so') | |
| mylib.myfunc.argtypes=[c_int,c_double,PointerWrapper(ndpointer(dtype=np.complex128,ndim=2,flags='C'))] | |
| mylib.myfunc.restype=c_int | |
| m=np.zeros((2,2),dtype=np.complex128) | |
| mylib.myfunc(1,0.5,m) | |
| print m |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment