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