首先载入dll:test = ctypes.windll.LoadLibrary('dlltest.dll')
若调用的dll中的函数的参数是int*:
a = ctypes.c_int(5)
#add是dll中的函数。int add(int* x, int y)
test.add(ctypes.byref(a),4)
############################################################
若返回值是char*:
C Code:
char* f(char * str)
{
return str;
}
--------------------------------------------------------------------------------
Python Code:
loadlibrary。。。
ff = dll.f
ff.argtypes = [ctypes.c_char_p]
ff.restype = ctypes.c_char_p #no []!!!!! and restype not restypes
input = "hello world"
output = ff(input)
print output
#################################################################
C Code:
char* t(char* ss)
{
int i = strlen(ss);
ss[1]='1';
ss[i]='G';
ss[i+1]='\0';
return ss;
}
//在这里只会改变ss所指的内容,但不会改变ss所指内容的长度!!!
---------------------------------------------------------------
Python Code:
loadlibrary。。。
t = dlltest.t
t.argtypes = [ctypes.c_char_p]
t.restype = ctypes.c_char_p
arg = "jjjjjjjjjjjjj"
print "input ",arg
#output = ctypes.c_char_p
output = t(arg)
print "output ",type(output)," ",output
#若是输出arg,后面的'G'不会显示,但前面修改成的'1'会表现。
#######################################################
对传入的char*所指的内容进行修改:
C Code:
char* t(char* ss)
{
char d[] = "12345678";
strcat(ss,d);
return ss;
}
--------------------------------------------------------------------------------------
Python Code:
dlltest = ctypes.windll.LoadLibrary('mydll.dll')
t = dlltest.t
t.argtypes = [ctypes.c_char_p]
t.restype = ctypes.c_char_p
p = ctypes.create_string_buffer(10) #!!!!!!!!
s = t(p)
#print type(s),len(s),type(p.value),len(p.value)
print "s:",s," / p.value:",p.value
#print p
此时,s和p.value都被修改了,并且其长度都是8。(实现了获取参数中被修改的char*值)