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.

Revisions

  1. yAngle created this gist Nov 11, 2011.
    10 changes: 10 additions & 0 deletions mylib.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    // 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;
    }
    21 changes: 21 additions & 0 deletions numpy_array.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    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