python怎么调用c函数 您所在的位置:网站首页 python函数通过什么调用 python怎么调用c函数

python怎么调用c函数

2022-04-21 21:06| 来源: 网络整理| 查看: 265

linux版的动态库

写个简单的C代码,test.c

#include  #include  char * printStr(const char *p,const char *q) {     printf("%s",p);     printf("%s",q);     return "djstava"; }

通过以下命令编译成动态链接库

gcc -fPIC -shared -o libtest.so test.c

相关推荐:《Python入门教程》

python3中调用

要调用C库中的函数,需要用到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"))

程序执行结果:

helloworld

程序解释

func.argtypes = (c_char_p,c_char_p) func.restype = c_char_p

这2句是分别设置参数数据类型和返回值类型,如果不进行设置,直接调用的话,参数可以正常接收,但是返回值永远是个int值,传入的字符串参数必须为encode("utf-8"),否则在c库中仅会打印为首字符。

handle = cdll.LoadLibrary('libtest.so') ret = handle.printStr("hello".encode("utf-8"),"world".encode("utf-8"))

windows版的动态库

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 > 8)&0x00FFFFFF);   return ~crc32val; }

然后打开VS X64工具命令行提示符,进入到C源码目录,分别执行以下两条命令,第一条命令是生成目标文件.obj,第二天命令是链接目标文件,生成动态库。

cl /c crc.c link /dll crc.obj

至此,dll文件就生成了,它就是我们需要的动态链接库,dll的调用跟so的方法一样。

您可能感兴趣的文章: python里怎么调用函数 python lambda怎么用 python怎么打开txt文件 python怎么用c 代码 python中怎么保留小数 python中的def语句是什么意思 python定义的类怎么用 python怎么创建文本文件 python怎么才能使随机整数不重复 python和c语言的区别是什么



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有