Windows下通过Python 3.x的ctypes调用C接口
生活随笔
收集整理的這篇文章主要介紹了
Windows下通过Python 3.x的ctypes调用C接口
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
????????在Python中可以通過(guò)ctypes來(lái)調(diào)用動(dòng)態(tài)庫(kù)中的C接口,具體操作過(guò)程如下:
????? ? 1.?使用vs2013創(chuàng)建一個(gè)加、減、乘、除的動(dòng)態(tài)庫(kù),并對(duì)外提供C接口,code內(nèi)容如下:
????? ? math_operations.hpp:
#ifndef TEST_DLL_1_MATH_OPERATIONS_HPP_
#define TEST_DLL_1_MATH_OPERATIONS_HPP_#define FBC_EXPORTS __declspec(dllexport)#ifdef __cplusplus
extern "C" {
#endifFBC_EXPORTS int add_(int a, int b);
FBC_EXPORTS int sub_(int a, int b);
FBC_EXPORTS int mul_(int a, int b);
FBC_EXPORTS int div_(int a, int b);#ifdef __cplusplus
}
#endif#endif // TEST_DLL_1_MATH_OPERATIONS_HPP_
????? ? math_operations.cpp:
#include "math_operations.hpp"
#include <iostream>FBC_EXPORTS int add_(int a, int b)
{fprintf(stdout, "add operation\n");return a + b;
}FBC_EXPORTS int sub_(int a, int b)
{fprintf(stdout, "sub operation\n");return a - b;
}FBC_EXPORTS int mul_(int a, int b)
{fprintf(stdout, "mul operation\n");return a * b;
}FBC_EXPORTS int div_(int a, int b)
{if (b == 0) {fprintf(stderr, "b can't equal 0\n");return -1;}return (a / b);
}
????? ? 2. python代碼如下:
import ctypeslib = ctypes.cdll.LoadLibrary("E:/GitCode/Python_Test/lib/rel/x64_vc12/Test_DLL_1.dll")a = 9; b = 3value = lib.add_(a, b)
print("add result:", value)
value = lib.sub_(a, b)
print("sub result:", value)
print("mul result:", lib.mul_(a, b))
print("div result:", lib.div_(a, b))
????? ? 執(zhí)行結(jié)果如下:
????? ? GitHub:??https://github.com/fengbingchun/Python_Test
總結(jié)
以上是生活随笔為你收集整理的Windows下通过Python 3.x的ctypes调用C接口的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Go语言基础介绍
- 下一篇: Ubuntu14.04下配置OpenGL