Skip to content

Instantly share code, notes, and snippets.

@yuhangwang
Forked from yangle/mylib.c
Created April 19, 2018 16:56
Show Gist options
  • Save yuhangwang/fef3ee4c4faef58e81326287088af1b0 to your computer and use it in GitHub Desktop.
Save yuhangwang/fef3ee4c4faef58e81326287088af1b0 to your computer and use it in GitHub Desktop.
ctypes examples
// 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;
}
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