Ctype为我们提供了一种在python中调用c的方法:

Step1:编写C代码:(testoutput.c)

#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>

void print();

void print()
{printf("Hello World!\n");}

int main ( void )
{
    FILE *output;
    output = fopen("output.txt","w");
    
    if(output == NULL)
    {
         printf("Open filefailure!\n");
         exit(1);
    }
 
    else
    {
         fprintf(output,"success\n");
    }
 
    fclose(output);

    return 0;
}

Step2:将C代码编译为动态链接库

gcc -m64 --share -o testoutput.dll -fPIC testoutput.c

注意这里的后缀名:windows下为.dll,而linux下为.so

Step3:在python中应用

from ctypes import *

t = CDLL('./testoutput.dll')

t.print()
t.main()

 

问题:初始的Step2编译没有 -m64 选项,结果python在CDLL那行运行错误:

 

问题原因是gcc编译器是32位的,但python是64位的(可以通过gcc -v 和 python -v 指令看出),而且此时32位gcc不支持 -m64 选项。

解决方案是装64位的gcc,这样达到了统一,问题解决。

P.S. 然而这样的话就没办法 -m32 了。。一个麻烦的办法是更改32位gcc和64位gcc在path路径中的先后顺序,这样在前面的总是会被调用,实现了手动的切换。。

在生成32位和64位的.dll文件后,如何在python中判断需要调用哪个呢,这时候需要用到struct.calcsize("P")语句:

import struct
is_64 = (64 == struct.calcsize("P") * 8)

(这里参考了https://www.likecs.com/show-204164801.html)

于是根据这个可以CDLL不同的dll文件。

 

*以上代码在win10上运行

 

posted on 2022-05-09 21:43  Duyy  阅读(245)  评论(0编辑  收藏  举报