新聞中心
linux版的動(dòng)態(tài)庫(kù)

10年積累的成都網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計(jì)經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶對(duì)網(wǎng)站的新想法和需求。提供各種問(wèn)題對(duì)應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先網(wǎng)站設(shè)計(jì)后付款的網(wǎng)站建設(shè)流程,更有長(zhǎng)白免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
寫(xiě)個(gè)簡(jiǎn)單的C代碼,test.c
#include#include char * printStr(const char *p,const char *q) { printf("%s",p); printf("%s",q); return "djstava"; }
通過(guò)以下命令編譯成動(dòng)態(tài)鏈接庫(kù)
gcc -fPIC -shared -o libtest.so test.c
相關(guān)推薦:《python入門教程》
python3中調(diào)用
要調(diào)用C庫(kù)中的函數(shù),需要用到ctypes這個(gè)模塊
# -*- coding: utf-8 -*-
from ctypes import *
handle = cdll.LoadLibrary('libtest.so')
func = handle.printStr
func.argtypes = (c_char_p,c_char_p)
func.restype = c_char_p
tmp = handle.printStr("hello".encode("utf-8"),"world".encode("utf-8"))
print(tmp.decode("utf-8"))程序執(zhí)行結(jié)果:
helloworld
程序解釋
func.argtypes = (c_char_p,c_char_p) func.restype = c_char_p
這2句是分別設(shè)置參數(shù)數(shù)據(jù)類型和返回值類型,如果不進(jìn)行設(shè)置,直接調(diào)用的話,參數(shù)可以正常接收,但是返回值永遠(yuǎn)是個(gè)int值,傳入的字符串參數(shù)必須為encode("utf-8"),否則在c庫(kù)中僅會(huì)打印為首字符。
handle = cdll.LoadLibrary('libtest.so')
ret = handle.printStr("hello".encode("utf-8"),"world".encode("utf-8"))windows版的動(dòng)態(tài)庫(kù)
Visual Studio編譯dll,在需要拋出的方法前加入__declspec(dllexport), 比如下面C代碼:
__declspec(dllexport) unsigned int crc32( const unsigned char *s, unsigned int len)
{
unsigned int i;
unsigned int crc32val=0xffffffff;
printf("len==%d\n",len);
for (i = 0; i < len; i ++)
crc32val = crc32_tab[(crc32val ^ s[i]) & 0xff] ^ ((crc32val >> 8)&0x00FFFFFF);
return ~crc32val;
}然后打開(kāi)VS X64工具命令行提示符,進(jìn)入到C源碼目錄,分別執(zhí)行以下兩條命令,第一條命令是生成目標(biāo)文件.obj,第二天命令是鏈接目標(biāo)文件,生成動(dòng)態(tài)庫(kù)。
cl /c crc.c link /dll crc.obj
至此,dll文件就生成了,它就是我們需要的動(dòng)態(tài)鏈接庫(kù),dll的調(diào)用跟so的方法一樣。
本文名稱:創(chuàng)新互聯(lián)Python教程:python怎么調(diào)用c函數(shù)
本文路徑:http://www.dlmjj.cn/article/djdeihd.html


咨詢
建站咨詢
