Python调用C/C++ DLL示例代码

27 阅读1分钟
  1. 先将 C/C++ 代码编译为 test.dll 动态链接库文件。
// header.h

#ifdef EXPORT_MY_DLL 
#define MY_API __declspec(dllexport)
#else 
#define MY_API __declspec(dllimport) 
#endif 
extern "C"
{
    MY_API int IntAdd(int, int);
}
// main.cpp

#include "header.h"
#define EXPORT_MY_DLL 

#include <stdio.h>
#include <math.h>
#include <iostream>
using namespace std;

int IntAdd(int a, int b)
{
    int c = a + b;
    cout << "a + b is " << c << endl;
    return c;
}

  1. 运行 python run.py 加载 DLL 并运行 DLL 中定义的函数。
# run.py

import ctypes

def test_myprogram():
    _lib = ctypes.cdll.LoadLibrary("C:/THE/PATH/TO/YOUR/test.dll")
    ans = _lib.IntAdd(2, 3)
    print(ans)