新聞中心
linux版的動態(tài)庫

10年積累的成都網(wǎng)站建設、成都網(wǎng)站設計經(jīng)驗,可以快速應對客戶對網(wǎng)站的新想法和需求。提供各種問題對應的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡服務。我雖然不認識你,你也不認識我。但先網(wǎng)站設計后付款的網(wǎng)站建設流程,更有長白免費網(wǎng)站建設讓你可以放心的選擇與我們合作。
寫個簡單的C代碼,test.c
#include#include char * printStr(const char *p,const char *q) { printf("%s",p); printf("%s",q); return "djstava"; }
通過以下命令編譯成動態(tài)鏈接庫
gcc -fPIC -shared -o libtest.so test.c
相關推薦:《python入門教程》
python3中調(diào)用
要調(diào)用C庫中的函數(shù),需要用到ctypes這個模塊
# -*- 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ù)據(jù)類型和返回值類型,如果不進行設置,直接調(diào)用的話,參數(shù)可以正常接收,但是返回值永遠是個int值,傳入的字符串參數(shù)必須為encode("utf-8"),否則在c庫中僅會打印為首字符。
handle = cdll.LoadLibrary('libtest.so')
ret = handle.printStr("hello".encode("utf-8"),"world".encode("utf-8"))windows版的動態(tài)庫
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;
}然后打開VS X64工具命令行提示符,進入到C源碼目錄,分別執(zhí)行以下兩條命令,第一條命令是生成目標文件.obj,第二天命令是鏈接目標文件,生成動態(tài)庫。
cl /c crc.c link /dll crc.obj
至此,dll文件就生成了,它就是我們需要的動態(tài)鏈接庫,dll的調(diào)用跟so的方法一樣。
本文名稱:創(chuàng)新互聯(lián)Python教程:python怎么調(diào)用c函數(shù)
當前路徑:http://www.5511xx.com/article/djdeihd.html


咨詢
建站咨詢
