Python使用Ctypes调用lib,怎么使用指针类型参数接收输出参数
推荐于2017-11-27 · 知道合伙人数码行家
huanglenzhi
知道合伙人数码行家
向TA提问 私信TA
知道合伙人数码行家
采纳数:117538
获赞数:517193
长期从事计算机组装,维护,网络组建及管理。对计算机硬件、操作系统安装、典型网络设备具有详细认知。
向TA提问 私信TA
关注
展开全部
本文演示了在python中调用C语言生成的动态库,返回结构体指针,并进行输出!
test.c(动态库源代码)
// 编译生成动态库: gcc -g -fPIC -shared -o libtest.so test.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct StructPointerTest
{
char name[20];
int age;
}StructPointerTest, *StructPointer;
StructPointer test() // 返回结构体指针
{
StructPointer p = (StructPointer)malloc(sizeof(StructPointerTest));
strcpy(p->name, "Joe");
p->age = 20;
return p;
}
编译:gcc -g -fPIC -shared -o libtest.so test.c
call.py(python调用C语言生成的动态库):
#!/bin/env python
# coding=UTF-8
from ctypes import *
#python中结构体定义
class StructPointer(Structure):
_fields_ = [("name", c_char * 20), ("age", c_int)]
if __name__ == "__main__":
lib = cdll.LoadLibrary("./libtest.so")
lib.test.restype = POINTER(StructPointer)
p = lib.test()
print "%s: %d" %(p.contents.name, p.contents.age)
最后运行结果:
[zcm@c_py #112]$make clean
rm -f *.o libtest.so
[zcm@c_py #113]$make
gcc -g -fPIC -shared -o libtest.so test.c
[zcm@c_py #114]$./call.py
Joe: 20
[zcm@c_py #115]$
test.c(动态库源代码)
// 编译生成动态库: gcc -g -fPIC -shared -o libtest.so test.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct StructPointerTest
{
char name[20];
int age;
}StructPointerTest, *StructPointer;
StructPointer test() // 返回结构体指针
{
StructPointer p = (StructPointer)malloc(sizeof(StructPointerTest));
strcpy(p->name, "Joe");
p->age = 20;
return p;
}
编译:gcc -g -fPIC -shared -o libtest.so test.c
call.py(python调用C语言生成的动态库):
#!/bin/env python
# coding=UTF-8
from ctypes import *
#python中结构体定义
class StructPointer(Structure):
_fields_ = [("name", c_char * 20), ("age", c_int)]
if __name__ == "__main__":
lib = cdll.LoadLibrary("./libtest.so")
lib.test.restype = POINTER(StructPointer)
p = lib.test()
print "%s: %d" %(p.contents.name, p.contents.age)
最后运行结果:
[zcm@c_py #112]$make clean
rm -f *.o libtest.so
[zcm@c_py #113]$make
gcc -g -fPIC -shared -o libtest.so test.c
[zcm@c_py #114]$./call.py
Joe: 20
[zcm@c_py #115]$
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询