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

时间:2023-01-15 18:27:39

        在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))

        执行结果如下:

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

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