Python调用C代码

本文介绍Python通过ctype模块调用C代码的方法。

一、代码

  1. C方法实现
    hello.h头文件
int __declspec(dllexport)  sayHello();
int __declspec(dllexport)  doubleValue(double value,double *result);

hello.c实现

#include "hello.h"

int  __declspec(dllexport) sayHello()
{
     return 110;
}

int __declspec(dllexport) doubleValue(double value,double *result){
    *result = value*2;
    return 0;
}

将C代码编译为dll文件“hello.dll”

  1. Python代码
import ctypes
from ctypes import*

lib = cdll.LoadLibrary("c:\\cache\\hello.dll")

print(lib.sayHello())

result = ctypes.c_double()
lib.doubleValue(ctypes.c_double(1.1),ctypes.byref(result))

print(result.value)

二、注意事项

(1)本文以Windows系统为例,其中__declspec(dllexport)是必需的。
(2)确保编译的dll与Python解释器兼容,比如同为64位。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容