how to call this dll in python

Shark ysystudio at gmail.com
Tue Nov 4 21:01:21 EST 2008


On Nov 4, 2:16 pm, "Mark Tolonen" <M8R-yft... at mailinator.com> wrote:
> "Shark" <ysystu... at gmail.com> wrote in message
>
> news:eb620337-0a9e-4d50-ab66-cfeeaba18dc4 at v39g2000pro.googlegroups.com...
>
> >I have a windows dll1.dll with a export function:
>
> > int f1(char filename,char **buf,int *bufLen)
> > {
> > int len;
> > //got the length of file anyway,such as 100
> > len = 100;//len = getLen(filename);
> > *buf = (char*)calloc(100);
> > *bufLen = len;
> > return 0;
> > }
>
> > then how can I call the f1 function with python.
> > thanks for your response.
>
> Here's a quick, tested example.  It's not pretty but demonstrates what you
> want:
>
> ===== begin C DLL code =======
> #include <string.h>
> #include <stdlib.h>
> #include <stdio.h>
>
> __declspec(dllexport)
> int get(const char* filename,char **buf,int *bufLen)
> {
>  int i,len;
>  printf("*buf before malloc=%p\n",*buf);
>  len = strlen(filename);
>  *buf = (char*)malloc(len);
>  *bufLen = len;
>  for(i=0;i<len-1;i++)
>       (*buf)[i]='a';
>  (*buf)[i]=0;
>  printf("*buf after malloc=%p\n",*buf);
>  return 5;
>
> }
>
> __declspec(dllexport)
> void release(char* buf)
> {
>  printf("buf[0]=%d\n",buf[0]);
>  printf("buf=%p\n",buf);
>  free(buf);}
>
> ===== end C DLL code =======
>
> ===== begin Python code =======
> from ctypes import *
> x = CDLL('x.dll')
> x.get.argtypes=[c_char_p,POINTER(POINTER(c_byte)),POINTER(c_int)]
> buf = POINTER(c_byte)()
> length = c_int()
> print x.get("hello.txt",byref(buf),byref(length))
> print repr(string_at(buf,length))
> buf[0]=55 # change first byte
> x.release.argtypes=[POINTER(c_byte)]
> x.release(buf)
> ===== end Python code =======
>
> sample output:
>
> *buf before malloc=00000000
> *buf after malloc=00C92940
> 5
> 'aaaaaaaa\x00'
> buf[0]=55
> buf=00C92940
>
> -Mark

thank you, Mark. I got it.



More information about the Python-list mailing list