Windows下通过Python 3.x的ctypes调用C接口

本文介绍如何通过Python的ctypes库调用预先创建好的C动态库中的加、减、乘、除运算接口。首先展示了C动态库的实现代码,然后提供了Python端的调用示例,最后给出了运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        在Python中可以通过ctypes来调用动态库中的C接口,具体操作过程如下:

        1. 使用vs2013创建一个加、减、乘、除的动态库,并对外提供C接口,code内容如下:

        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" {
#endif

FBC_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 ctypes

lib = ctypes.cdll.LoadLibrary("E:/GitCode/Python_Test/lib/rel/x64_vc12/Test_DLL_1.dll")

a = 9; b = 3

value = 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))

        执行结果如下:


        GitHub:  https://github.com/fengbingchun/Python_Test

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值