python利用ctypes的指针传入int型列表和string类型列表到c语言中

下面这个方法是将c语言的函数编译为动态链接库,然后python调用得到结果。这个c语言中没有main函数,是因为python只需要调用它的方法。

将它和c++结合,用c++操作这个python的list,就需要用到extern “C”了。。。后续会出~~

如果有大神可以不用extern”C”直接调用c++的,请留言,感谢分享

#include 

void get_str_list(int n, char *b[2])
{
    printf("in c start");
    for(int i=0;iprintf("%s", *(b+i));
        printf("\n");
    }
    printf("in c end");
}

void get_point_int(int n, int *b)
{
    printf("in c start\n");
    for(int i=0;iprintf("%d", *(b+i));
        printf("\n");
    }
    printf("in c end\n");
}

void get_point_str(int n, char *b[])
{
    printf("in c start\n");
    for(int i=0;iprintf("%s", *(b+i));
        printf("\n");
    }
    printf("in c end");
}

将上面的c语言编译为动态链接库

gcc -o hello2.so -shared -fPIC c_p.c

对应的python代码(这里注意ll后面是动态链接库的路径)

from ctypes import *
ll = cdll.LoadLibrary
lib = ll("./12_23_ctype_list/hello2.so")
n = 3
str1 = c_char_p(bytes("nihao", 'utf-8'))
str2 = c_char_p(bytes("shijie", 'utf-8'))
lists = [str1, str2]
print(enumerate(lists))
a = (c_char_p*2)(str1, str2)
lib.get_str_list(2, a)

b = [1,23,345]
b_arr = (c_int*3)(*b)
lib.get_point_int(3, b_arr)

c = ["hello", "world", "ni", "hao"]
str_c1 = c_char_p(bytes("hello", "utf-8"))
str_c2 = c_char_p(bytes("world", "utf-8"))
str_c3 = c_char_p(bytes("ni", "utf-8"))
str_c4 = c_char_p(bytes("hao", "utf-8"))
c = [str_c1, str_c2, str_c3, str_c4]
c_arr = (c_char_p*4)(*c)  # 传入一个python的list的指针
lib.get_point_str(4, c_arr)

结果:

at 0x7f78598fe3a8>
in c startnihao
shijie
in c endin c start
1
23
345
in c end
in c start
hello
world
ni
hao
in c end

附上一幅python类型转ctypes类型再转c++类型的汇总图:

python利用ctypes的指针传入int型列表和string类型列表到c语言中_第1张图片

你可能感兴趣的:(python基础,c++和java基础)