python使用ctypes调用gcc编译的dll之g++编译c++代码

发布时间 2023-07-25 17:44:15作者: 平平无奇小辣鸡

1、在windows系统将cpp代码编译成可供python调用的dll

1.1 新建header.h代码如下

#pragma once
#define DllExport __declspec( dllexport )
extern "C"
{
    DllExport void hello_world(void);
}

/*
#pragma once 用来防止某个头文件被多次include,这条指令就能够保证头文件被编译一次

extern "C" 在C++源文件中的语句前面加上extern "C",表明它按照类C的编译和连接规约来编译和连接,而不是C++的编译的连接规约。

__declspec(dllexport)关键字从 DLL 中导出数据、函数、类或类成员函数。导出后可供其它DLL或者exe使用。
*/

1.2 新建test.c代码如下

#include <iostream>
#include <string.h>
#include "header.h"

void hello_world() {
    // 打印hello world
    std::cout << "hello world" << std::endl;
}
1.3 编译C++代码
g++ test.cpp -fPIC -shared -o test.dll
1.5 运行python代码
python test.py
# 运行后会打印hello world

2、在Linux系统将cpp代码编译成可供python调用的.so库

2.1 新建header.h代码如下

#pragma once

extern "C"
{
    void hello_world(void);
}

2.2 新建test.c代码如下

#include <iostream>
#include <string.h>
#include "header.h"

void hello_world() {
    // 打印hello world
    std::cout << "hello world" << std::endl;
}

2.3 编译C++代码

g++ test.cpp -fPIC -shared -o test.so

2.4 新建test.py代码如下

import ctypes

# 下面两种加载动态库的方式都可以使用
# test = ctypes.cdll.LoadLibrary('./test.so')
test = ctypes.CDLL('./test.so')

test.hello_world()

2.5 运行python代码

python test.py
# 运行后会打印hello world

#pragma once相关参考
https://www.cnblogs.com/zhangbaochong/p/5164800.html

extern "C"相关参考
https://www.cnblogs.com/skynet/archive/2010/07/10/1774964.html
https://learn.microsoft.com/en-us/cpp/cpp/extern-cpp?view=msvc-170

__declspec(dllexport)相关参考
https://learn.microsoft.com/zh-cn/cpp/build/exporting-from-a-dll-using-declspec-dllexport?view=msvc-170

https://www.cnblogs.com/lisuyun/p/5484017.html

加载dll或so的动态库
https://docs.python.org/zh-tw/3/library/ctypes.html#loading-shared-libraries

c++参数使用可参考
https://gcc.gnu.org/onlinedocs/gcc-12.3.0/gcc/Code-Gen-Options.html
https://gcc.gnu.org/onlinedocs/gcc-12.3.0/gcc/Link-Options.html
https://www.runoob.com/w3cnote/gcc-parameter-detail.html