Python笔记 ＋

# 再谈通过ctypes向C函数传指针

ctypes

## 用bytes string

``````>>> from ctypes import *
>>> libc = CDLL('libc.so.6')
a>>> libc.printf(b"abcde 12345\n")
abcde 12345
12
``````

``````#include

void print_str(char *str)
{
printf("%s\n",str);
}
``````

``````>>> from ctypes import *
>>> cc = CDLL('./c2.so')
>>> cc.print_str(b'abcde')
abcde
6
>>> cc.print_str(b'abcde1234567')
abcde1234567
13
``````

## 用 c_char_p 对象

``````>>> a = c_char_p(b'abcde 12345 kkkkk')
>>> cc.print_str(a)
abcde 12345 kkkkk
18
``````

## 用struct.pack封装结构体指针

``````#include

typedef struct {
int a;
int b;
double c;
} abc;

void show_abc(abc *in)
{
printf("%d %d %f\n",in->a,in->b,in->c);
}
``````

``````>>> from ctypes import *
>>> cc = CDLL('./c2.so')
>>>
>>> import struct
>>> cc.show_abc(struct.pack('iid',1,2,3))
1 2 3.000000
13
``````

struct.pack返回的就是一个已经格式化后的byte string，'iid'是格式化字符串，对应C代码中的abc结构体，必须要对应哈。

## 传函数指针

``````/* for qsort in libc */
int
cmp_int(const void *keyval, const void *datum)
{
return (*(int*)keyval - *(int*)datum);
}``````

``````def test_libc_qsort(self):
libc = ctypes.CDLL('libc.so.6')
libc.qsort(self.dca02,
len(self.a02),
ctypes.sizeof(ctypes.c_int),
self.get_sort().cmp_int)
self.assertEqual(list(self.ca02), sorted(self.a02))
libc.qsort(self.dca03,
len(self.a03),
ctypes.sizeof(ctypes.c_int),
self.get_sort().cmp_int)
self.assertEqual(list(self.ca03), sorted(self.a03))``````

-- EOF --

### 留言区
{"ft_lang_label":"__label__zh","ft_lang_prob":0.6615708,"math_prob":0.9102398,"size":1857,"snap":"2021-43-2021-49","text_gpt3_token_len":918,"char_repetition_ratio":0.11332974,"word_repetition_ratio":0.088607594,"special_character_ratio":0.3231018,"punctuation_ratio":0.21135646,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.97147185,"pos_list":[0,1,2],"im_url_duplicate_count":[null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-10-21T11:29:29Z\",\"WARC-Record-ID\":\"<urn:uuid:07428537-7e04-4af2-bb86-e626692b9cf3>\",\"Content-Length\":\"25495\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:9797a141-3787-4598-80c7-c8994f1c135f>\",\"WARC-Concurrent-To\":\"<urn:uuid:3dfbf3b6-4d5d-49d9-b8bc-99cbd0cd6454>\",\"WARC-IP-Address\":\"148.72.212.244\",\"WARC-Target-URI\":\"https://www.pynote.net/archives/2961\",\"WARC-Payload-Digest\":\"sha1:WN7QGNHRAN4K5LGDWQTIEPCHMONUL774\",\"WARC-Block-Digest\":\"sha1:D4EYPD6IMG6GE7HSSCGNAM5VLUG72VK5\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-43/CC-MAIN-2021-43_segments_1634323585405.74_warc_CC-MAIN-20211021102435-20211021132435-00130.warc.gz\"}"}