python从动态库中返回并输出字符串


如何传递一个数组给动态库中的函数,并通过传递的数组返回字符串呢?
这里演示一种间接的方法。不知道有没有更直接的方法?
1 动态库中的函数定义:

struct ss {
char name[10];
int age;
};

void GetString(struct ss *p)
{
strcpy(p->name, "Hello dll.");
p->age = 25;
}

编译生成dll.so:  gcc -fPIC -O2 -shared dll.c -o dll.so

2 python中调用实例:

from ctypes import *

class ss(Structure):
_fields_=[
("name", c_byte*10),
("age", c_int),
]
#name定义为c_byte*10, 存储的是interger,想要输出为字符串比较麻烦


fileName = "/home/primax/Desktop/Work/Test/python/dll.so"
lib = cdll.LoadLibrary(fileName)

t = ss()
lib.GetString(pointer(t))
tt = create_string_buffer(11)

memmove(tt, byref(t), 10)
temp = tt.value.__str__()[2:-1]
print(temp)

打印输出:
Hello dll.



免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM